Reputation: 12914
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?
Upvotes: 6
Views: 11225
Reputation: 12644
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()
.
Upvotes: 3
Reputation: 828002
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);
Upvotes: 11
Reputation: 1269
It does not. You could define one as:
function strncmp(a, b, n){
return a.substring(0, n) == b.substring(0, n);
}
Upvotes: 3
Reputation: 44832
function strncmp(a, b, length) {
a = a.substring(0, length);
b = b.substring(0, length);
return a == b;
}
Upvotes: 1
Reputation: 225202
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 ) );
}
Upvotes: 2