Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript equivalent to C strncmp (compare string for length)

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 strings for up to length chars and determine if they were equal as far as length went.

Does JavaScript have an equivalent built in function?

like image 295
Daniel Bingham Avatar asked Jan 24 '10 18:01

Daniel Bingham


People also ask

Can Javascript compare strings?

The inbuilt javascript methods can be used to compare two strings. For case-insensitive string comparison, toUpperCase and toLowerCase methods are used, which compare the value of string using equality operator after converted to uppercase and lowercase, respectively.

How do you equate two strings in Javascript?

The localeCompare() method compares two strings in the current locale. The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

Does strcmp compare length?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0.

What will strncmp () function do?

strncmp compares two character strings ( str1 and str2 ) using the standard EBCDIC collating sequence. The return value has the same relationship to 0 as str1 has to str2 . If two strings are equal up to the point at which one terminates (that is, contains a null character), the longer string is considered greater.


2 Answers

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

like image 124
Christian C. Salvadó Avatar answered Oct 01 '22 22:10

Christian C. Salvadó


It does not. You could define one as:

function strncmp(a, b, n){
    return a.substring(0, n) == b.substring(0, n);
}
like image 36
Eli Avatar answered Oct 01 '22 23:10

Eli