Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimum way to compare strings in JavaScript? [duplicate]

I am trying to optimize a function which does binary search of strings in JavaScript.

Binary search requires you to know whether the key is == the pivot or < the pivot.

But this requires two string comparisons in JavaScript, unlike in C like languages which have the strcmp() function that returns three values (-1, 0, +1) for (less than, equal, greater than).

Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search?

like image 830
HRJ Avatar asked Jan 30 '10 10:01

HRJ


People also ask

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

Can we use == to compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

How do I compare two strings in JavaScript?

To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.

Is it safe to compare JavaScript strings?

Firstly, you are safe to compare strings that contain characters from Basic Multilangual Plane (including the ASCII characters) using regular comparison operators === , == or utility function Object.is() . Both str1 and str2 contain ASCII characters, so you can safely compare them using comparison operators.


1 Answers

You can use the localeCompare() method.

string_a.localeCompare(string_b);  /* Expected Returns:   0:  exact match  -1:  string_a < string_b   1:  string_a > string_b   */ 

Further Reading:

  • MDN: String.prototype.localeCompare
  • Stack Overflow - Is there a JavaScript strcmp()?
  • Tutorials Point: JavaScript String - localeCompare() Method
like image 60
Daniel Vassallo Avatar answered Sep 22 '22 02:09

Daniel Vassallo