码迷,mamicode.com
首页 > 编程语言 > 详细

javascript正则表达式对象方法 compile() exec() test()的比较

时间:2016-11-21 20:53:25      阅读:189      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!