Comparing Strings using String Methods
localeCompare() method compares two strings based on their Unicode values, taking into account locale-specific rules. The method returns a negative number if the first string is sorted before the second string, a positive number if the first string is sorted after the second string, and 0 if the strings are equal. Here’s an example:
const str1 = "apple"; const str2 = "banana"; const result = str1.localeCompare(str2); console.log(result); // Output: -1
In this example,
localeCompare() is used to compare the strings “apple” and “banana”. Since “apple” comes before “banana” in alphabetical order, the result is -1.
Using other String Methods
indexOf(). These methods return boolean values indicating whether a string begins with, ends with, contains, or includes a specific substring. Here’s an example:
const str = "Hello, World"; console.log(str.startsWith("Hello")); // Output: true console.log(str.endsWith("World")); // Output: true console.log(str.includes("o")); // Output: true console.log(str.indexOf("W")); // Output: 7
In this example, the string methods are used to check if the string “Hello, World” starts with “Hello”, ends with “World”, includes the letter “o”, and find the index of the letter “W”.
Comparing Strings using Comparison Operators
>=, which can be used to compare strings. These operators compare strings based on their Unicode values. Here’s an example:
const str1 = "apple"; const str2 = "banana"; console.log(str1 < str2); // Output: true console.log(str1 > str2); // Output: false
In this example, the strings “apple” and “banana” are compared using the
> operators. Since “apple” comes before “banana” in alphabetical order,
str1 < str2 returns
str1 > str2 returns
Case-Sensitive String Comparison
toUpperCase() methods before comparing them. Here’s an example:
const str1 = "apple"; const str2 = "APPLE"; console.log(str1 === str2); // Output: false console.log(str1.toLowerCase() === str2.toLowerCase()); // Output: true
In this example, the strings “apple” and “APPLE” are compared using the
Hi all, my name is Angelika and I am one of the authors of the EasyTechh website. Like the rest of our team I am incredibly ambitious and I love helping people.
That’s why I write here and not only here 😉 I write interesting and useful for people articles in the IT sphere and a little bit about life.