JavaScript strncasecmp
Binary safe string comparison
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 39 4041 42 43 44 4546 47 48 49 50 | function strncasecmp (argStr1, argStr2, len) { // Binary safe string comparison // // version: 1008.1718 // discuss at: http://phpjs.org/functions/strncasecmp // + original by: Saulo Vallory // + input by: Nate // + bugfixed by: Onno Marsman // % note: Returns < 0 if str1 is less than str2 ; > 0 if str1 is greater than str2 , and 0 if they are equal. // * example 1: strncasecmp('Price 12.9', 'Price 12.15', 2); // * returns 1: 0 // * example 2: strncasecmp('Price 12.09', 'Price 12.15', 10); // * returns 2: -1 // * example 3: strncasecmp('Price 12.90', 'Price 12.15', 30); // * returns 3: 8 // * example 4: strncasecmp('Version 12.9', 'Version 12.15', 20); // * returns 4: 8 // * example 5: strncasecmp('Version 12.15', 'Version 12.9', 20); // * returns 5: -8 var diff, i = 0; var str1 = (argStr1+'').toLowerCase().substr(0,len); var str2 = (argStr2+'').toLowerCase().substr(0,len); if (str1.length !== str2.length) { if (str1.length < str2.length) { len = str1.length; if (str2.substr(0, str1.length) == str1) { return str1.length - str2.length; // return the difference of chars } } else { len = str2.length; // str1 is longer than str2 if (str1.substr(0, str2.length) == str2) { return str1.length - str2.length; // return the difference of chars } } } else { // Avoids trying to get a char that does not exist len = str1.length; } for (diff = 0, i=0; i < len; i++) { diff = str1.charCodeAt(i) - str2.charCodeAt(i); if (diff !== 0) { return diff; } } return 0; } |
Examples
» Example 1
Running
1 | strncasecmp('Price 12.9', 'Price 12.15', 2); |
Should return
1 |
» Example 2
Running
1 | strncasecmp('Price 12.09', 'Price 12.15', 10); |
Should return
1 | -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 strncasecmp goodness in JavaScript.

Slight grammar error:
Kevin van Zonneveld
24 Sep '08