JavaScript substr
Returns part of a string
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 | function substr (str, start, len) { // Returns part of a string // // version: 909.322 // discuss at: http://phpjs.org/functions/substr // + original by: Martijn Wieringa // + bugfixed by: T.Wild // + tweaked by: Onno Marsman // + revised by: Theriault // * example 1: substr('abcdef', 0, -1); // * returns 1: 'abcde' // * example 2: substr(2, 0, -6); // * returns 2: false // Add: (?) Use unicode.semantics and/or unicode.runtime_encoding (e.g., with string wrapped in "binary" or "Binary" class) to // allow access of binary (see file_get_contents()) by: charCodeAt(x) & 0xFF (see https://developer.mozilla.org/En/Using_XMLHttpRequest )// Fix: Handle 4-byte characters str += ''; var end = str.length; if (start < 0) { start += end; } end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start); // PHP returns false if start does not fall within the string. // PHP returns false if the calculated end comes before the calculated start. // PHP returns an empty string if start and end are the same. // Otherwise, PHP returns the portion of the string from start to end. return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end); } |
Examples
» Example 1
Running
1 | substr('abcdef', 0, -1); |
Should return
1 | 'abcde' |
» Example 2
Running
1 | substr(2, 0, -6); |
Should return
1 | false |
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 substr goodness in JavaScript.
Had a bit of difficulty when this function was passed an integer instead of a string since
1 | .substring |
I fixed the error thusly:
1 | return (""+f_string).substring(f_start, f_length); |
instead of:
1 | return f_string.substring(f_start, f_length); |
forcing f_string to be a string, since this is how the PHP version treats the first parameter.
[CODE="php"]
substr(1234,2,1) = 3;
[/CODE]
hope this helps.


Kevin van Zonneveld
5 Sep '08