JavaScript strcspn
Finds length of initial segment consisting entirely of characters not found in mask. If start or/and length is provide works like strcspn(substr($s,$start,$len),$bad_chars)
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 | function strcspn (str, mask, start, length) { // Finds length of initial segment consisting entirely of characters not found in mask. If start or/and length is provide works like strcspn(substr($s,$start,$len),$bad_chars) // // version: 1008.1718 // discuss at: http://phpjs.org/functions/strcspn // + original by: Brett Zamir (http://brett-zamir.me) // * example 1: strcspn('abcdefg123', '1234567890'); // * returns 1: 7 // * example 2: strcspn('123abc', '1234567890'); // * returns 2: 3 start = start ? start : 0; var count = (length && ((start + length) < str.length)) ? start + length : str.length; strct: for (var i=start, lgth=0; i < count; i++) { for (var j=0; j < mask.length; j++) { if (str.charAt(i).indexOf(mask[j]) !== -1) { continue strct; } } ++lgth; } return lgth; } |
Examples
» Example 1
Running
1 | strcspn('abcdefg123', '1234567890'); |
Should return
1 | 7 |
» Example 2
Running
1 | strcspn('123abc', '1234567890'); |
Should return
1 | 3 |
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 strcspn goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: @HalfWinter, Paulo Freitas, Andros Peña Romo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>