×

compile()方法用于在执行脚本时编译正则表达式

作者:andy0012020.01.19来源:Web前端之家浏览:5642评论:0
关键词:compile()

javascript中的compile()方法用于在执行脚本时编译正则表达式,也可用于重新编译和更改正则表达式。

语法:

RegExpObject.compile(RegExp, modifier)

参数:

● regexp:指定正则表达式。

● modifier:规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。

示例:更改初始字符串,然后使用compile()方法再次更改它

<script>
	var str="Every man in the world! Every woman on earth!";
	var patt=/man/g;
	var str2=str.replace(patt,"person");
	document.write(str2+"<br>");
	patt=/(wo)?man/g;
	patt.compile(patt); 
	str2=str.replace(patt,"person");
	document.write(str2);
</script>

上面的示例中,在字符串中全局搜索 "man",并用 "person" 替换。然后通过 compile() 方法,改变正则表达式,用 "person" 替换 "man" 或 "woman"。

输出:

Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/jsjsj9e8r90808.html

网友评论文明上网理性发言 已有0人参与

发表评论: