Is there a JavaScript strcmp()?
What about
str1.localeCompare(str2)
Javascript doesn't have it, as you point out.
A quick search came up with:
function strcmp ( str1, str2 ) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + input by: Steve Hilder
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: gorthaur
// * example 1: strcmp( 'waldo', 'owald' );
// * returns 1: 1
// * example 2: strcmp( 'owald', 'waldo' );
// * returns 2: -1
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/
Of course, you could just add localeCompare if needed:
if (typeof(String.prototype.localeCompare) === 'undefined') {
String.prototype.localeCompare = function(str, locale, options) {
return ((this == str) ? 0 : ((this > str) ? 1 : -1));
};
}
And use str1.localeCompare(str2)
everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales
and options
if you care about that.
localeCompare()
is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:
str1 < str2 ? -1 : +(str1 > str2)
This is an order of magnitude faster than localeCompare()
on my machine.
The +
ensures that the answer is always numeric rather than boolean.
var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;
Usage: strcmp(string1, string2)
Result: 1
means string1 is bigger, 0
means equal, -1
means string2 is bigger.
This has higher performance than String.prototype.localeCompare
Also, numeric:true
makes it do logical number comparison