views:

2693

answers:

4

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 );

As this question is really just me complaining, I wouldn't normally waste your time with it, but I wasted 30 minutes looking for such a function (who wants people pointing at your code and laughing "This doof re-implemented strcmp!"), so I thought it might be nice for there to be a page on the Web (like stackoverflow) explicitly states so.

+3  A: 

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/

voyager
+1  A: 

You're not alone - other people have done this before.

The PHP.JS project actually has done this for many other common functions, as well. It's a handy resource.

Reed Copsey
Wow, what great, quick responses! I think it was seeing something on PHP.JS that first gave me some idea that it didn't exist. I just wondered why none of the JS docs that I checked mentioned it.Thanks much, overflowers!
+7  A: 

how about

str1.localeCompare(str2)
newacct
localeCompare() looked good, but it looked like it was MS-only, or not in the standard at best.
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 (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String#Methods_unrelated_to_HTML)
newacct
newacct is absolutely correct. This seems to be ECMAScript standard. Probably the best solution in this case.
coderjoe
A: 

cant remove this post

richard