JavaScript对象:JavaScript compile() 方法

返回到:JavaScript对象:JavaScript RegExp 对象

定义和用法

compile() 方法用于在脚本执行过程中编译正则表达式。

compile() 方法也可用于改变和重新编译正则表达式。

语法

RegExpObject.compile(regexp,modifier)
参数描述
regexp正则表达式。
modifier规定匹配的类型。”g” 用于全局匹配,”i” 用于区分大小写,”gi” 用于全局区分大小写的匹配。

除了 Opera 浏览器外,其他浏览器都支持 compile() 方法。

实例

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程(Web176.com)</title>
</head>
<body>

<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>

</body>
</html>

作者:terry,如若转载,请注明出处:https://www.web176.com/javascriptbook/jsarrtips/2915.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年8月9日 下午5:28
下一篇 2021年8月9日 下午5:44

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注