JavaScript substr_compare
Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters
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 | function substr_compare (main_str, str, offset, length, case_insensitivity) { // Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters // // version: 910.813 // discuss at: http://phpjs.org/functions/substr_compare // + original by: Brett Zamir (http://brett-zamir.me) // + derived from: strcasecmp, strcmp // * example 1: substr_compare("abcde", "bc", 1, 2); // * returns 1: 0 if (!offset && offset !== 0) { throw 'Missing offset for substr_compare()'; } if (offset < 0) { offset = main_str.length + offset; } if (length && length > (main_str.length - offset)) { return false; } length = length || main_str.length - offset; main_str = main_str.substr(offset, length); str = str.substr(0, length); // Should only compare up to the desired length if (case_insensitivity) { // Works as strcasecmp main_str = (main_str+'').toLowerCase(); str = (str+'').toLowerCase(); if (main_str == str) { return 0; } return (main_str > str) ? 1 : -1; } // Works as strcmp return ( ( main_str == str ) ? 0 : ( ( main_str > str ) ? 1 : -1 ) );} |
Examples
Running
1 | substr_compare("abcde", "bc", 1, 2); |
Should return
1 |
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_compare goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>