Skip to content
Fix Code Error

Optimum way to compare strings in JavaScript?

March 13, 2021 by Code Error
Posted By: Anonymous

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?

Solution

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
Answered By: Anonymous

Related Articles

  • How to prevent scrolling the whole page?
  • Form field border-radius is not working only on the…
  • How to set HTML5 required attribute in Javascript?
  • How do I include certain conditions in SQL Count
  • How does PHP 'foreach' actually work?
  • Reference — What does this symbol mean in PHP?
  • What's wrong with 'template int compare(char p1 [N],…
  • Is there any possible way to loop strcmp function in…
  • Design DFA accepting binary strings divisible by a…
  • Error: undefined Unable to resolve module
  • Equals(=) vs. LIKE
  • For-each over an array in JavaScript
  • How do the PHP equality (== double equals) and…
  • What are the undocumented features and limitations…
  • Quicksort with Python
  • How to solve Internal Server Error in Next.Js?
  • Sort all the elements of the list according to the…
  • How does tuple comparison work in Python?
  • How to generate a random string of a fixed length in Go?
  • What is an optional value in Swift?
  • What does this symbol mean in JavaScript?
  • Getting the closest string match
  • C++ Compare char array with string
  • In my quicksort implementation using C++ vectors, is…
  • Why does C++ code for testing the Collatz conjecture…
  • General problems with Google Optimize in React / Next.js
  • How can I pass a wct test while rearranging children…
  • How to internationalize a React Native Expo App?
  • is there a way to use the forwarding of std::less…
  • Google Optimize not triggering when running on localhost
  • Three.js: Cannot display mesh created with texture array
  • C++ Switch statement to assign struct values
  • How to filter a RecyclerView with a SearchView
  • Active tab issue on page load HTML
  • Aurelia UX showcase app fails to load
  • Fastest way to iterate over all the chars in a String
  • What's the difference between utf8_general_ci and…
  • How can I parse a CSV string with JavaScript, which…
  • What does "Fatal error: Unexpectedly found nil while…
  • What are the applications of binary trees?
  • Memcached vs. Redis?
  • Smart way to truncate long strings
  • Comparing boxed Long values 127 and 128
  • What is a plain English explanation of "Big O" notation?
  • How can I return pivot table output in MySQL?
  • JavaScript hashmap equivalent
  • Assembly - JG/JNLE/JL/JNGE after CMP
  • NSPhotoLibraryUsageDescription key must be present…
  • Simple way to transpose columns and rows in SQL?
  • How to compare arrays in JavaScript?
  • Html ordered list 1.1, 1.2 (Nested counters and…
  • Quicksort: Choosing the pivot
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Comparison between Corona, Phonegap, Titanium
  • How to write a PHP ternary operator
  • When dealing with Localizable.stringsdict, why…
  • python max function using 'key' and lambda expression
  • Save foreign key to other Model with hasMany relation
  • How can I configure Storybook.js Webpack with…
  • removing string array words from a txt file
  • Java : Sort integer array without using Arrays.sort()
  • data.table vs dplyr: can one do something well the…
  • Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap
  • Howto: Clean a mysql InnoDB storage engine?
  • How do I merge two dictionaries in a single…
  • Using less in a polymer-dart application
  • Returning a Promise from a Computed Property
  • Not Equal to This OR That in Lua
  • Problems with swapping
  • How to compare strings in an "if" statement?
  • Trouble with qsort with key/value structs in a btree
  • getting error while updating Composer
  • Trying to read files in directory, directory just…
  • What am I doing wrong in my C binary search code?…
  • Insert the succeeded word before conjunction 'and'…
  • How to resolve "Could not find schema information…
  • String comparison using '==' vs. 'strcmp()'
  • Ubuntu apt-get unable to fetch packages
  • Fundamental difference between Hashing and…
  • Adding asterisk to required fields in Bootstrap 3
  • Javascript negative number
  • How to sort strings in JavaScript
  • Dynamic type languages versus static type languages
  • update file based on a key in C
  • How to show multiple select options when user select…
  • Using method function in v-if
  • Python for loop skips iteration
  • Clang vs GCC - which produces faster binaries?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Ternary operators in JavaScript without an "else"
  • Is there some way to test my grammar which refer to…
  • Efficiently replace all accented characters in a string?
  • Text Progress Bar in the Console
  • How to implement a in JavaScript?
  • What's the difference between equal?, eql?, ===, and ==?
  • JavaScript ternary operator example with functions
  • Vue - Update Data on Bootstrap Table Custom Component
  • center 3 items on 2 lines
  • Pandas Merging 101
  • What is a NullReferenceException, and how do I fix it?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Open and write data to text file using Bash?

Next Post:

Convert list to tuple in Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error