Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
javascript

What is the string localeCompare() method in JavaScript?

Sarvech Qadir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The string.localeCompare() method is one of the built-in methods of the String class. This method compares the strings lexicographicallyComparison of a string or character in alphabetical order.

Syntax:

reference.localeCompare(compare)

Parameters

compare: The string that we compare lexicographically with reference.

Return value

The localeCompare() method returns the following values: 1, 0, -1.

Key guidelines:

  1. If string reference is lexicographically greater than string compare, the method returns 1.

  2. If string reference is lexicographically less than string compare, the method returns -1.

  3. If string reference is lexicographically equal to string compare, the method returns 0.

Code

Let’s look at the following coding example:

// alphabetically x comes before y.
a = 'x'.localeCompare('y');
// should be -1
console.log(a)
// alphabetically x comes after q.
b = 'x'.localeCompare('q');
// should be 1
console.log(b)
// comparing x with x
c = 'x'.localeCompare('x');
// should be 0
console.log(c)

RELATED TAGS

string
javascript

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring