JavaScript Comparing strings | localeCompare() method examples

Use Javascript localeCompare() method to compares two strings in the current locale. This method returns 0 if both the strings are equal.

Note:

  • The locale is based on the language settings of the browser.
  • This method does case-sensitive comparing.

Syntax

Return Value:

  • -1 if the reference string is sorted before the compareString
  • 0 if the two strings are equal
  • 1 if the reference string is sorted after the compareString

Example of JavaScript Comparing strings

The example of comparing the 2 strings using the localeCompare() method in js.

Example of JavaScript Comparing strings

JavaScript string compare case insensitive

The simplest way to do it (if you’re not worried about special Unicode characters) is to call toUpperCase:

Q: How to compare two strings character by character in javascript?

Answer: 1) how can I check two shuffle string have the same characters As I have.

2) If not have the same characters then which are the characters not exist in the second sting

Using a while loop seems a reasonable solution:

In JavaScript string not equal is != same as !==

They are subtly not the same.

!= checks the value
!== checks the value and type

Q: How to compare two strings in javascript if condition?

Answer: You could do like that: Using “===” triple equals.

Or you could use an array and check with an existential quantifier like

Complete code

Output: Matched

Q: What is the best way to compare two strings in JavaScript?

Answer: The best way To compare two strings in JavaScript is to use the localeCompare() method.

Do comment if you have any questions or suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.