本文详解JavaScript中字符串replace方法结合正则表达式进行全局替换的技巧。通过实例演示如何正确使用g标志实现所有匹配项替换,并介绍使用RegExp构造函数动态生成正则对象的场景,涵盖括号捕获组及特殊字符转义处理。
[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
正则 replace 全局替换与动态生成详解
下面展示使用数组配合正则替换实现的代码示例。
[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
假设需要将字符串 "hand hand hand" 转换为 "hand.gif hand.gif hand.gif"。
首先尝试直接使用 replace 方法:
str=str.replace("hand","hand.gif");
执行结果为:hand.gif hand hand
可以看到,这种方式只替换了第一次出现的内容。:(
考虑到 replace 方法支持正则表达式,于是尝试使用正则进行替换。
引用
返回根据正则表达式进行文字替换后的字符串的复制。
stringObj.replace(rgExp, replaceText)
于是编写如下代码:
str = str.replace(/hand/,"hand.gif")
发现无效,结果与直接字符串替换一致。
要实现全部替换,必须添加全局标志 g,
str = str.replace(/hand/g,"hand.gif")
测试发现仍然不行:(
参考了JavaScript的replace方法与正则表达式结合应用讲解这篇文章后,终于明白,原来要用()括起来,才会替换()里的东东。正确的写法如下:
str = "hand hand hand";
str=str.replace(/(hand)/g,"hand.gif");
document.write(str);
正确输出:hand.gif hand.gif hand.gif。
JS的正则另一种写法是使用RegExp:
如str=str.replace(/(hand)/g,"hand.gif");
等同于:
reg = new RegExp("(hand)","g");
str = str.replace(reg,'hand.gif');
当正则表达式需要动态生成时,更适合使用这种方式。
扩展一下:
str = "hand'( hand'( hand'(";
str=str.replace(/(hand\'\()/g,"hand.gif");
document.write(str);
str = 'hand\'( hand\'( hand\'(';
str=str.replace(/(hand\'\()/g,"hand.gif");
document.write(str);