How to Compare Strings in JavaScript

Introduction to JavaScript String Comparison

Within JavaScript, there exists a collection of built-in functions that enable the manipulation of client-side web user data, facilitating the fulfillment of user needs without the reliance on backend systems. One of these built-in functions is the localeCompare method, designed for comparing two strings in the JavaScript environment. When this method yields a result of 0, it signifies that the two string values are identical. In scenarios where the first string precedes the second, the method will output -1, whereas if the second string comes before the first, the output will be 1.

Syntax:

The localeCompare function in JavaScript is used to compare two strings. It provides a standard way to carry out this comparison within client-side scripts.

Example

<html>
<head>
<script>
function name()
{
----some javascript logic codes---
var s="";
var s1="";
var result=s.localeCompare(s1);
--some script codes---
}
</script>
</head>
<body>
</body>
</html>

The provided examples demonstrate the fundamental syntax employed in comparing strings using the localeCompare function within the script logic of an HTML web page. While the function is capable of standalone usage without additional function declarations, it is essential to utilize the <script> tag to initialize the method within the web page.

How Does String Comparison in JavaScript Function?

JavaScript programming in web development makes use of various built-in methods for client-side scripting. JavaScript allows for both strict comparisons and comparisons that involve type conversion. The === operator is employed for strict comparisons to determine if two operands not only have the same data type but also the same content, like identical string values. Typically, the == operator is utilized for value comparison, acting similarly to strict comparison but first coercing both operands into a common data type before the actual comparison. Additionally, JavaScript employs other relational operators such as <=, which first coerces the first operand into its primitive type before evaluating the expression with the two operands.

Sorting strings typically follows the standard lexicographical order based on their Unicode values. To be considered equal, two strings must have identical character sequences, matching lengths, and the same characters at corresponding positions. Similarly, two numbers are deemed strictly equal if their values are identical. Occasionally, NaN serves as an operand value for strings, and it is important to note that positive and negative zeros are considered equal. When comparing string values of different types, it is essential to employ strict comparisons. In cases of object operands, JavaScript verifies their references to determine equality, confirming equality only when both operands point to the same memory instance.

When the operands differ, the relational operator mandates them to be of the same type. In JavaScript, if two operands are being compared and are not of the same type, the language automatically converts them to a compatible type for comparison. When comparing objects or instances, JavaScript examines their internal references; if they point to distinct memory locations, they are considered unequal. Identity operators yield true only when the operands are strictly identical, with no allowance for type conversion. Conversely, the non-identity operator (!==) returns true when the operands are both different and have different types. The standard equality operators, like == and !=, employ the Abstract Equality Comparison Algorithm to establish the correlation between two operands.

When operands of different types are used, the algorithm will automatically convert them to a shared type before performing the comparison.

Examples of JavaScript Compare Strings

Below are several instances illustrating how to perform string comparisons in JavaScript.

Example 1

Example

<!DOCTYPE html>
<html>
<body>
<p>Welcome Users</p>
<ul>
<li> If string s is ordered prior to string s1, the result will be -1.</li>
<li>If the two strings are identical, the result will be 0. </li>
<li>If string s is ordered subsequent to string s1, the result will be 1.</li>
</ul>
<p>Welcome to the page</p>
<button onclick="sample()">Click the button</button>
<p id="demo"></p>
<script>
function sample() {
var s = "Yshakan";
var s1 = "Hello";
var result = s1.localeCompare(s);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>

Output

After clicking the button:

Case-Insensitive String Comparison

For instance, it is possible to prompt a user to enter names and subsequently verify if those names exist in our database. In such scenarios, the comparison of the two strings does not require them to be exactly the same; variations in cases are permissible. These instances exemplify situations where case-insensitive comparisons of strings are necessary.

When comparing strings in a case-insensitive manner, it involves disregarding the distinction between uppercase and lowercase letters. JavaScript utilizes the functions toLowerCase and toUpperCase to perform case-insensitive string comparisons.

Example 2

Example

// Function to compare a and b
function compareStrings(a, b){
   
    // This condition will return true only if a and b hold true from equality
    if(a == b){
        return 'Both strings are equal';
    }
    
    return 'Both strings are not equal';
}

const str1 = 'Javascript';
const str2 = 'JavaScript';
const str3 = 'Javascript';
const str4 = 'Typescript'

//Expected output: Both strings are equal
console.log(compareStrings(str1.toUpperCase(), str2.toUpperCase()));

//Expected output: Both strings are equal
console.log(compareStrings(str1.toLowerCase(), str3.toLowerCase()));

//Expected output: Both strings are not equal
console.log(compareStrings(str1, str4));

Output

When the toUpperCase function is used on str1 and str2 in the previous instance, the comparison results in the expression JAVASCRIPT == JAVASCRIPT being true, indicating that the strings are identical when converted to uppercase. The equality operator (==) verifies if the two strings are equal.

In this instance, when comparing str1 and str3 following the application of the toUpperCase function to both, the assertion javascript == javascript remains valid. This is due to the fact that both strings are the same when converted to lowercase.

In the previous instance, when comparing str1 with str4, the statement "JavaScript == Typescript" results in being false due to the distinction between the strings "JavaScript" and "Typescript."

Conclusion

When working with JavaScript, it is important to compare variables declared as string data types using comparison operators. These operators are designed to evaluate the variables and return a boolean value based on the comparison. This process can involve various conditional operators to determine the relationship between the variables.

Input Required

This code uses input(). Please provide values below: