JavaScript strspn
Finds length of initial segment consisting entirely of characters found in mask. If start or/and length is provided works like strspn(substr($s,$start,$len),$good_chars)
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 | function strspn (str1, str2, start, lgth) { // Finds length of initial segment consisting entirely of characters found in mask. If start or/and length is provided works like strspn(substr($s,$start,$len),$good_chars) // // version: 1008.1718 // discuss at: http://phpjs.org/functions/strspn // + original by: Valentina De Rosa // + improved by: Brett Zamir (http://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 var found; var stri; var strj; var j = 0; var 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; } |
Examples
» Example 1
Running
1 | strspn('42 is the answer, what is the question ...', '1234567890'); |
Should return
1 | 2 |
» Example 2
Running
1 | strspn('foo', 'o', 1, 2); |
Should return
1 | 2 |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have strspn goodness in JavaScript.
I think this should add the other two args...
[CODE="Javascript"]
strspn('42 is the answer, what is the question ...', '1234567890');
strspn("foo", "o", 1, 2); // 2
function strspn(str1, str2, start, lgth){
// http://kevin.vanzonneveld.net
// + original by: Valentina De Rosa
// % note 1: Good start, but still missing the 3rd & 4th argument which came to PHP in version 4.3.0
// * example 1: strspn('42 is the answer, what is the question ...', '1234567890');
// * returns 1: 2
var found;
var stri;
var strj;
var j = 0;
var 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;
}[/CODE]


Kevin van Zonneveld
30 Dec '08