JS String Compare


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

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


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

var s = "endmemo";
alert(s=="endmemo"); //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 = "endmemo";
alert(s.toLowerCase()=="endmemo"); //true
alert(s.toUpperCase()=="ENDMEMO"); //true
alert(s.toUpperCase()=="endmemo"); //false


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

var s = "endmemo.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 = "endmemo.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("endmemo.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("endmemo.com");
var p = s.lastIndexOf('m') //p = 10
p = s.lastIndexOf("g") //p = -1
p = s.lastIndexOf("e") //p = 4


endmemo.com © 2024  | Terms of Use | Privacy | Home