JS String Compare


"==" operator can be used to compare whether two strings are equal.

var s = "perschon";
alert(s=="perschon"); //true


"===" operator can be used to compare whether two strings are identical, including type and value.

var s = "perschon";
alert(s=="perschon"); //true
var s2 = "44";
alert(s2===44); //false


Comparison using other comparison operators:

var s = "abb";
alert(s<"bbb"); //true
alert(s<"Bbb"); //false
alert(s>"44"); //true

In fact, only the first characters are used for comparison according to their ASCII numbers.

toLowerCase() and toUpperCase() can be used to do case insensitive comparison:

var s = "perschon";
alert(s.toLowerCase()=="perschon"); //true
alert(s.toUpperCase()=="Perschon"); //true
alert(s.toUpperCase()=="perschon"); //false


match() method can be used for string containment comparison, return matches:

var s = "perschon.com";
var m = s.match(/.m/g); //m is an array returned
m.valueOf(); //dm,em,om


Similarly, search() method can be used to search whether a string is a substring of another string, it returns the first occurrence position found:

var s = "perschon.com";
var p = s.search("dm"); //p is 2
var p = s.search(/e.o/); //p is 4
var p = s.search(/\s\d/); //p is -1, not found


indexOf() method: Search string and return the first occurrence position, if not found, return -1:

var s = new String("perschon.com");
var p = s.indexOf('m') //p = 3
p = s.indexOf("g") //p = -1
p = s.indexOf("mo") //p = 5


lastIndexOf() method: Search string from the end, and return the position of the first found occurrence, if not found, return -1:

var s = new String("perschon.com");
var p = s.lastIndexOf('m') //p = 10
p = s.lastIndexOf("g") //p = -1
p = s.lastIndexOf("e") //p = 4


convert.idontcarewhatyouthink.net © 2021  Terms of Use | Home