请知悉:本文最近一次更新为 10年 前,文中内容可能已经过时。
<script type="text/JavaScript">
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"))
</script>

以上代码实现的是全局的正则替换。

<script type="text/JavaScript">
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/i, "W3School"))
</script>

以上代码实现的是不区分大小写进行一次替换。

<script type="text/JavaScript">  
var p = /$/mg;
var s = '1n2n3n4n5n6';
alert(p.test(s)); //显示为true
alert(RegExp.rightContext.replace(/x0A/g, '\a')); //显示a2a3a4a5a6
alert(RegExp.leftContext); //显示为竖的2345
alert(RegExp.rightContext); //显示为6

var p = /$/g;
var s = '1n2n3n4n5n6';
alert(p.test(s)); //显示为true
alert(RegExp.rightContext.replace(/x0A/g, '\a')); //什么都不显示
alert(RegExp.leftContext); //显示为竖的123456
alert(RegExp.rightContext); //什么都不显示

var p = /^/mg;
var s = '1n2n3n4n5n6';
alert(p.test(s)); //显示为true
alert(RegExp.rightContext.replace(/x0A/g, '\a')); //显示为1a2a3a4a5a6
alert(RegExp.leftContext); //显示为竖的12345
alert(RegExp.rightContext); //显示为6
</script>

以上代码实现的是/m影响的^$的分割方式

1g 表示该表达式将用来在输入字符串中查找所有可能的匹配,返回的结果可以是多个。如果不加/g最多只会匹配一个
2i 表示匹配的时候不区分大小写
3m 表示多行匹配,什么是多行匹配呢?就是匹配换行符两端的潜在匹配。影响正则中的^$符号

以上内容整理自:
https://www.w3school.com.cn/jsref/jsref_replace.asp
https://aabc99.blog.163.com/blog/static/163010810201132185918581/


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《JavaScript-正则批量替换》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌