JavaScript Program to Compare Two Strings Lexicographically
Last Updated :
29 Feb, 2024
This JavaScript program compares two strings lexicographically, meaning it checks if one string comes before or after the other in alphabetical order. Lexicographical comparison is based on the Unicode value of each character in the strings.
The program should return a positive value if the first string comes after the second string, a negative value if the first string comes before the second string, and zero if the strings are equal.
Using LocaleCompare Method
JavaScript’s localeCompare() method compares two strings lexicographically and returns a value indicating their relative ordering.
Example: The below code example Uses the LocaleCompare Method to Compare Two Strings Lexicographically in JavaScript.
Javascript
function compareStrings(str1, str2) {
return str1.localeCompare(str2);
}
console.log(compareStrings( "apple" , "banana" ));
console.log(compareStrings( "apple" , "apple" ));
|
Using Custom Comparison
In this approach, we manually compare the characters of the strings one by one to determine their lexicographical order.
Example: The below code example Uses the Custom Comparison Method to Compare Two Strings Lexicographically in JavaScript.
Javascript
function compareStrings(str1, str2) {
for (let i = 0; i < Math.min(str1.length, str2.length); i++) {
if (str1[i] !== str2[i]) {
return str1[i].charCodeAt(0) - str2[i].charCodeAt(0);
}
}
return str1.length - str2.length;
}
console.log(compareStrings( "apple" , "banana" ));
console.log(compareStrings( "apple" , "apple" ));
|
Share your thoughts in the comments
Please Login to comment...