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 = "perschon.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 = "perschon.com R language tutorial"; var x = s.replace("R language","javascript"); //x is "perschon.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 "); //perschon.com javascript language tutorial //$0 is the whole match of the pattern var x2 = s.replace(/\sR(.+ge)\s/,"javascript$0"); //perschon.com javascript R language tutorial
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
Methods of javascript RegExp object include:
var s = "perschon.com"; var reg=/\.c/; var result = reg.exec(s); alert(result); //.c
var s = "perschon.com"; var reg=/\.c/; var result = reg.test(s); alert(result); true
Use variables in string match
var str = "perschon.com"; var pat= new RegExp("me","g"); if (str.match(pat)) { alert("m"); }
var s = "perschon.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: