标签:javascript compile exec test
compile() 方法用于在脚本执行过程中编译正则表达式,也可用于改变和重新编译正则表达式。
exec() 方法用于检索字符串中的正则表达式的匹配。找到则返回一个数组,未找到则返回null。
test() 方法用于检测一个字符串是否匹配某个模式。返回true 或 false.
语法:
compile():
RegExpObject.compile(regexp,modifier)
regexp 正则表达式。
modifier 规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。
RegExpObject.exec(string)
string 要检索的字符串。
RegExpObject.test(string)
string 要检测的字符串。
<script type="text/javascript">
var str="Every man in the world! Every woman on earth!";
patt=/man/g;
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>
输出结果:Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!
<script type="text/javascript">
var str = "good jjdky";
var patt = new RegExp("jjdky","g");
var result;
while ((result = patt.exec(str)) != null) {
document.write(result);
document.write("<br />");
document.write(patt.lastIndex);
}
</script>
输出结果:jjdky
10
<script type="text/javascript">
var str = "good jjdky";
var patt1 = new RegExp("jjdky");
var result = patt1.test(str);
document.write("Result: " + result);
</script>
输出结果:Result: true本文出自 “申请博客的第一天” 博客,请务必保留此出处http://6965535.blog.51cto.com/6955535/1874921
javascript正则表达式对象方法 compile() exec() test()的比较
标签:javascript compile exec test
原文地址:http://6965535.blog.51cto.com/6955535/1874921