📜  equalsignorecase 打字稿 - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:37.774000             🧑  作者: Mango

equalsIgnoreCase() in Javascript

equalsIgnoreCase() is a method in Java which is used to compare two strings ignoring their case. In Javascript, there is no built-in method like equalsIgnoreCase(), but we can use other methods to achieve the same functionality.

Example:

Let's see a simple example of comparing two strings in Javascript, ignoring their case:

let str1 = "Hello world";
let str2 = "HELLO WORLD";
if(str1.toUpperCase() === str2.toUpperCase()){
   console.log("Both strings are equal");
}
else{
   console.log("Strings are not equal");
}

In the above code snippet, we are converting both strings to uppercase using the toUpperCase() method and then comparing them. If both are equal, then we are printing "Both strings are equal", otherwise, "Strings are not equal".

Using a custom function:

We can also create a custom function equalsIgnoreCase() to compare two strings in Javascript. Here's an example:

function equalsIgnoreCase(str1, str2){
    return str1.toUpperCase() === str2.toUpperCase();
}

let str1 = "Hello world";
let str2 = "HELLO WORLD";

if(equalsIgnoreCase(str1, str2)){
   console.log("Both strings are equal");
}
else{
   console.log("Strings are not equal");
}

In the above code snippet, we are defining a custom function equalsIgnoreCase() which takes two parameters, str1 and str2, and converts both strings to uppercase before comparing them.

Conclusion:

In this tutorial, we have seen how to ignore case while comparing two strings in Javascript using the toUpperCase() method and by creating a custom function. While there is no built-in method like equalsIgnoreCase() in Javascript, we can still achieve the same functionality.