Is there an equivalent in JavaScript to the C function strnc开发者_如何学编程mp
? 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?
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);
}
Since ECMAScript 2015 there is startsWith()
:
str.startsWith(searchString[, position])
This covers the very frequent use case where the length of the comparison is the length of the searchString
, and only a boolean return value is required (strcmp()
returns an integer to indicate relative order, instead.)
The Mozilla doc page also contains a polyfill for String.prototype.startsWith()
.
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 ) );
}
you could always substring the strings first, and then compare.
function strncmp(a, b, length) {
a = a.substring(0, length);
b = b.substring(0, length);
return a == b;
}
精彩评论