PHP's strspn in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { strspn } from 'locutus/php/strings/strspn'.

Or with CommonJS: const { strspn } = require('locutus/php/strings/strspn')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1strspn('42 is the answer, what is the question ...', '1234567890')2
2strspn('foo', 'o', 1, 2)2

Here's what our current TypeScript equivalent to PHP's strspn looks like.

export function strspn(str1: string, str2: string, start?: number, lgth?: number): number {
// discuss at: https://locutus.io/php/strspn/
// parity verified: PHP 8.3
// original by: Valentina De Rosa
// improved by: Brett Zamir (https://brett-zamir.me)
// example 1: strspn('42 is the answer, what is the question ...', '1234567890')
// returns 1: 2
// example 2: strspn('foo', 'o', 1, 2)
// returns 2: 2

let found
let stri
let strj
let j = 0
let i = 0

start = start ? (start < 0 ? str1.length + start : start) : 0
lgth = lgth ? (lgth < 0 ? str1.length + lgth - start : lgth) : str1.length - start
str1 = str1.substr(start, lgth)

for (i = 0; i < str1.length; i++) {
found = 0
stri = str1.substring(i, i + 1)
for (j = 0; j <= str2.length; j++) {
strj = str2.substring(j, j + 1)
if (stri === strj) {
found = 1
break
}
}
if (found !== 1) {
return i
}
}

return i
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star