Regular Expression object initialization:
var reg = new RegExp(pattern, modifier); var reg = /pattern/modifier;
String has some methods that support regular expression, include
var s = "endmemo.com"; var m = s.match(/.m/g); //m is an array returned m.valueOf(); //dm,em,om m = s.match(/nd(.+)o\./); alert(m[0]); //ndmemo. alert(m[1]); //mem, matched pattern in ()
var s = "endmemo.com R language tutorial"; var x = s.replace("R language","javascript"); //x is "endmemo.com javascript tutorial" var x = s.replace(/\sR.+ge\s/,"javascript"); //same result, using regular expression //using $1, $2 to replace the matches in brackets var x = s.replace(/\sR(.+ge)\s/," javascript$1 "); //endmemo.com javascript language tutorial //$0 is the whole match of the pattern var x2 = s.replace(/\sR(.+ge)\s/,"javascript$0"); //endmemo.com javascript R language tutorial
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
Methods of javascript RegExp object include:
var s = "endmemo.com"; var reg=/\.c/; var result = reg.exec(s); alert(result); //.c
var s = "endmemo.com"; var reg=/\.c/; var result = reg.test(s); alert(result); true
Use variables in string match
var str = "endmemo.com"; var pat= new RegExp("me","g"); if (str.match(pat)) { alert("m"); }
var s = "endmemo.com"; var reg=/\.c/; var result = s.match(reg); alert(result[0]); //true reg.compile("dm","g"); result = s.match(reg); alert(result[0]);
var reg = /^\dend/ig; alert(reg.global); //true alert(reg.multiline); //false
Regular Expression Modifiers: