By jonathan


2009-07-24 18:30:45 8 Comments

Can anyone verify this for me? JavaScript does not have a version of strcmp(), so you have to write out something like:

 ( str1 < str2 ) ? 
            -1 : 
             ( str1 > str2 ? 1 : 0 );

5 comments

@Anonymous 2019-01-16 04:20:45

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

@1'' 2013-07-20 18:10:00

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.

@stackunderflow 2013-09-03 18:14:26

Two bugs: does not return 0 for str1 == str2, does not return 1 for str1 > str2

@1'' 2013-09-03 18:16:59

@stackunderflow What are you suggesting that it returns in those cases?

@stackunderflow 2013-09-03 18:22:45

@1" I suggest it should be useful as a comparefun in Array.prototype.sort, but actually the values need not be 1 and -1, just negative or positive as I just reread the standard.

@1'' 2013-09-03 18:23:36

@stackunderflow I'm using it successfully in a sorting function. What is the bug that you are experiencing?

@Felype 2015-07-13 12:23:58

@stackunderflow that line is correct, it returns -1 if str1<str2 and then the return value of str1>str2 which from boolean to int is 0 or 1.

@jfren484 2016-07-21 17:56:22

This will return -1, false, or true instead of -1, 0, or 1. To get it to return numbers always, tweak it like this: str1 < str2 ? -1 : +(str1 > str2)

@jfren484 2016-07-21 20:30:49

One more thing (I'm using this in code I'm writing right now, so I've been perfecting it): just be aware that this is a case-sensitive comparison ('Foo' will come before 'bar' but 'Bar' will come after 'foo'). That corresponds to OP's question about strcmp, but many people may come here looking for a case-agnostic comparison.

@Jonathan Gilbert 2016-11-15 16:37:25

Here's an even cleaner-looking expression: (str1 > str2) - (str1 < str2)

@newacct 2009-07-24 18:38:08

What about

str1.localeCompare(str2)

@jonathan 2009-07-24 18:49:32

localeCompare() looked good, but it looked like it was MS-only, or not in the standard at best.

@newacct 2009-07-24 19:37:13

what standard are you looking at? it seems to be in ECMA-262 standard section 15.5.4.9, as well as in the mozilla Javascript reference (developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…)

@coderjoe 2009-07-24 21:26:34

newacct is absolutely correct. This seems to be ECMAScript standard. Probably the best solution in this case.

@Varda Elentári 2016-03-23 16:21:49

localeCompare() sometimes behaves differently on each browser.

@T.J. Crowder 2017-04-14 09:51:23

@VardaElentári: Only for characters that have no lexical ordering in the given locale. For characters that do and browsers that don't restrict what parts of Unicode they use, results are consistent and defined by ECMA-402 and Unicode.

@Kip 2018-09-13 13:57:16

Update 9 years later- seems this has partial support in IE6+ (covering the single-arg version), full support in IE11, and all other decent browsers of course support it: caniuse.com/#search=localecompare

@Esteban Küber 2009-07-24 18:34:00

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.

@Tokimon 2014-06-30 08:45:38

I think this is a nice way of handling it (feature detection and polyfill FTW), but if micro speed performance is so important, as for the need of this method, then I am a little puzzled that == is used and not === since the latter avoid type conversion and hence is that micro second faster.

@Kip 2018-09-13 14:01:55

a note on the polyfill-- localeCompare is not case-sensitive, so to make the polyfill also not case-sensitive you might do something like- var a = this.toUpperCase(); var b = str.toUpperCase(); return ((a == b) ? 0 : ((a > b) ? 1 : -1));

@Panos Papadopoulos 2013-06-12 14:55:45

How about:

String.prototype.strcmp = function(s) {
    if (this < s) return -1;
    if (this > s) return 1;
    return 0;
}

Then, to compare s1 with 2:

s1.strcmp(s2)

@Relaxing In Cyprus 2014-06-23 12:14:43

It would help if you said why they shouldn't do what they did. I could understand if they were altering how an existing function method worked, but in this case they are adding a new one.

@Christopher 2019-02-04 18:33:51

Extending prototypes unconditionally like this is generally a big no-no.

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6253697 View
  • 7809 Score
  • 93 Answer
  • Tags:   javascript arrays

85 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

63 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

61 Answered Questions

[SOLVED] How to replace all occurrences of a string?

26 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

86 Answered Questions

[SOLVED] How do JavaScript closures work?

4 Answered Questions

Sponsored Content