JavaScript Strings Comparison

JavaScript Strings Comparison

·

2 min read

ebay


String Comparison

To check whether a string is greater than another, dictionary or lexicographical ordering is used.

Lexicographical ordering is when strings are compared letter-by-letter.

See the example below:

console.log( 'Z' > 'A' ); // true
console.log( 'Z' > 'a' ); // false
console.log( 'Bee' > 'Be' ); // true

In the example above, 'Z' > 'A' but 'Z' < 'a'. This is so because a lowercase letter is always greater than the uppercase

The algorithm to compare two strings is systematic.

console.log('ridicules' > 'ridiculous'); // false

The example above is false because ridicul === ridicul but ridicule < ridiculo because e < o.

Characters unique code

Each character has its unique numeric code. The unique numeric code is what is actually used for comparison.

The syntax to find a character unique numeric code is

str.codePointAt(pos)

See the example below:

// code is also based on character case
console.log( "a".codePointAt(0) ); // 97
console.log( "A".codePointAt(0) ); // 65

console.log( "z".codePointAt(0) ); // 122
console.log( "Z".codePointAt(0) ); // 90

You can also get a character by its numeric code.

The syntax is shown below:

String.fromCodePoint(code)

See the example below:

console.log( String.fromCodePoint(97) ); // a
console.log( String.fromCodePoint(65) ); // A

Alternatively, you can add Unicode characters by their codes using \u followed by the hex code.

See the example below:

// 90 is 5a in hexadecimal system
console.log( '\u005a' ); // Z

Let's iterate through each unique numeric code to see their characters.

See the example below:

let str = '';

for (let i = 65; i <= 220; i++) {
  str += String.fromCodePoint(i);
}
console.log(str);
/*
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜ
*/

In the example above, Capital characters go first, then a few special ones, lower case characters, etc.

Now it is obvious why a > Z.

All modern browsers (IE10- requires the additional library Intl.js) support the internationalization standard ECMA-402.

Locale String Comparison

The str1.localeCompare(str2) returns an integer indicating whether str1 is less, equal, or greater than str2 according to the language rules.

Syntax

str1.localeCompare(str2)
  • Returns -num if str1 < str2.
  • Returns +num if str1 > str2.
  • Returns 0 if str1 === str2.

See the example below:

console.log( 'Österreich'.localeCompare('Zealand') ); // -1

Buy me a Coffee


ebay.jpg