views:

304

answers:

5

Is there an equivalent in Javascript to the C function strncmp? Strncmp takes two string arguments and an integer length argument. It would compare the two string up to length and determine if they were equal as far as length went.

Does javascript have an equivalent built in function?

+1  A: 

you could always substring the strings first, and then compare.

Toad
+2  A: 

You could easily build that function:

function strncmp(str1, str2, n) {
  str1 = str1.substring(0, n);
  str2 = str2.substring(0, n);
  return ( ( str1 == str2 ) ? 0 :
                              (( str1 > str2 ) ? 1 : -1 ));
}

An alternative to the ternary at the end of the function could be the localeCompare method e.g return str1.localeCompare(str2);

CMS
I built it a little differently, but thanks. Just wanted to make sure I wasn't reinventing the wheel first.
Daniel Bingham
+1  A: 

It doesn't but you can find one here, along with many other useful javascript functions.

function strncmp ( str1, str2, lgth ) {
    // Binary safe string comparison  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/strncmp
    // +      original by: Waldo Malqui Silva
    // +         input by: Steve Hilder
    // +      improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +       revised by: gorthaur
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strncmp('aaa', 'aab', 2);
    // *     returns 1: 0
    // *     example 2: strncmp('aaa', 'aab', 3 );
    // *     returns 2: -1
    var s1 = (str1+'').substr(0, lgth);
    var s2 = (str2+'').substr(0, lgth);

    return ( ( s1 == s2 ) ? 0 : ( ( s1 > s2 ) ? 1 : -1 ) );
}
Carl Norum
+1  A: 
function strncmp(a, b, length) {
   a = a.substring(0, length);
   b = b.substring(0, length);

   return a == b;
}
Andreas Bonini
+1  A: 

It does not. You could define one as:

function strncmp(a, b, n){
    return a.substring(0, n) == b.substring(0, n);
}
Eli