Skip to content

JavaScript localeCompare | String method

  • by

JavaScript localeCompare() method is used to compares two strings in the current locale. This method returns a number indicating whether a reference string comes before or after or is the same as the given string in sorted order.


This method method returns sort order -1, 1, or 0 (for before, after, or equal) and current locale is based on the language settings of the browser.

Return Value

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

JavaScript localeCompare

Simple example code.

<!DOCTYPE html>
<html lang="en">
    let text1 = "ab";
    let text2 = "cd";
    let text3 = "ab"

    let res1 = text1.localeCompare(text2);
    let res2 = text2.localeCompare(text1);
    let res3 = text1.localeCompare(text3);



JavaScript localeCompare String method

More example

const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase

console.log(a.localeCompare(b)); // 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' })); // 0

Do comment if you have any doubts or suggestions on this Js string method.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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