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?
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.
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).
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.
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.
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);
It does not. You could define one as:
function strncmp(a, b, n){
return a.substring(0, n) == b.substring(0, n);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With