3、compile():既可以改变检索模式,也可以添加或删除第二个参数。
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
patt1.compile("d");
document.write(patt1.test("The best things in life are free"));
修饰符:
1、g:执行全局匹配查找所有匹配而非在找到第一个匹配后停止;
在使用 "g" 参数时,exec() 的工作原理如下:
找到第一个 "e",并存储其位置
如果再次运行 exec(),则从存储的位置开始检索,并找到下一个 "e",并存储其位置
var patt1=new RegExp("e","g");
do
{
result=patt1.exec("The best things in life are free");
document.write(result);
}
while (result!=null)
全局替换:
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
返回的结果:Welcome to W3School! We are proud to announce that W3Schoolhas one of the largest Web Developers sites in the world.使用正则表达式:
name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'");