JavaScript is equivalent to C strncmp (compare string for length)

Is there an equivalent in JavaScript for the strncmp C strncmp ? strncmp accepts two string arguments and an integer argument length . It would compare two strings to the exact length character and determine if they were equal to length .

Does JavaScript have an equivalent inline function?

+4
source share
6 answers

You can easily create this 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 end of a function can be the localeCompare method, for example return str1.localeCompare(str2);

+8
source

This is not true. You can define it as:

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

It is not, but you can find here here , as well as 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 ) ); } 
+2
source

you can always substring strings first and then compare.

+1
source
 function strncmp(a, b, length) { a = a.substring(0, length); b = b.substring(0, length); return a == b; } 
+1
source

Since ECMAScript 2015 has startsWith() :

 str.startsWith(searchString[, position]) 

This refers to a very common use case where the length of the comparison is equal to the length of the searchString and only a boolean return value is required ( strcmp() returns an integer to indicate a relative order instead).

Mozilla's document page also contains a polyfill for String.prototype.startsWith() .

0
source

Source: https://habr.com/ru/post/1299256/


All Articles