Use Javascript localeCompare() method to compares two strings in the current locale. This method returns 0 if both the strings are equal.
Note:
- The locale is based on the language settings of the browser.
- This method does case-sensitive comparing.
Syntax
string_1.localeCompare(String_2)
Return Value:
- -1 if the reference string is sorted before the compareString
- 0 if the two strings are equal
- 1 if the reference string is sorted after the compareString
Example of JavaScript Comparing strings
The example of comparing the 2 strings using the localeCompare() method in JS.
<!DOCTYPE html>
<html>
<head>
<script>
var str1 = "ABCD";
var str2 = "ABCD";
var n = str1.localeCompare(str2);
alert(n)
//console.log( myString );
</script>
</head>
</html>
JavaScript string compare case insensitively
The simplest way to do it (if you’re not worried about special Unicode characters) is to call toUpperCase
:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
Q: How to compare two strings character by character in javascript?
Answer: 1) how can I check two shuffle string have the same characters As I have.
2) If not have the same characters then which are the characters not exist in the second sting
Using a while loop seems a reasonable solution:
var str1 = "ansar@#//1";
var str2 = "@#//sanra12";
s1 = str1.split('');
s2 = str2.split('');
var i = s1.length + 1;
while (i--) {
if (s2.indexOf(s1[i]) >= 0)
s2.splice(s2.indexOf(s1[i]), 1);
}
console.log(s2)
In JavaScript string not equal is != same as !==
They are subtly not the same.
!=
checks the value!==
checks the value and type
'1' != 1 // false (these two are the same)
'1' !== 1 // true (these two are **not** the same).
Q: How to compare two strings in javascript if condition?
Answer: You could do like that: Using “===” triple equals.
if (str === "txt1" || str === "txt2") {
}
Or you could use an array and check with an existential quantifier like
if (["txt1", "txt2"].some(a => a === str)) {
Complete code
<!DOCTYPE html>
<html>
<head>
<script>
var str = "txt1";
if (str === "txt1" || compare === "txt2") {
alert("Matched")
} else {
alert("Not Matched")
}
//console.log( myString );
</script>
</head>
</html>
Output: Matched
Q: What is the best way to compare two strings in JavaScript?
Answer: The best way To compare two strings in JavaScript is to use the localeCompare() method.
var str1 = "cd";
var str2 = "ab";
var n = str1.localeCompare(str2);
Do comment if you have any questions or suggestions on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version