PHP's strspn in JavaScript

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

module.exports = function strspn (str1, str2, start, lgth) {
// discuss at: https://locutus.io/php/strspn/
// 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
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/strings/strspn'). You could also require the strings module in full so that you could access strings.strspn instead.

If you intend to target the browser, you can then use a module bundler such as Parcel, webpack, Browserify, or rollup.js. This can be important because Locutus allows modern JavaScript in the source files, meaning it may not work in all browsers without a build/transpile step. Locutus does transpile all functions to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

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

« More PHP strings functions


Star