一:正则表达对象方法
1:compile()方法 //编译正则表达式
实例:在字符串中全局搜索“man”,并用“person”替换,然后通过compile()方法,改变正则表达式,用person替换“woman”:
1 <script type="text/javascript> 2 var str="Every man in the world! Every woman on earth!"; 3 4 patt=/man/g; //在字符串中全局搜索"man" 5 str2=str.replace(patt,"person"); //把搜索匹配到的man替换成person 6 document.write("替换后的字符串为:"+str2+"<br>"); 7 8 patt=/(wo)?man/g; //全局搜索匹配woman或者是man 9 patt.compile(patt); //通过complle()方法改变正则表达式 10 str2=str.replace(patt,"person");//将匹配到的字符串替换成person 11 document.write(str2); 12 </script>
输出:
Every person in the world! Every woperson on earth! every person in the world! every person on earth!
2:JavaScript exec()方法 //用于检索字符串中的正则表达式的匹配
返回一个数组,其中存放匹配的结果,如果未找到匹配,则返回值为null.
实例:全局检索字符串中的W3School:
<script type="text/javascript"> var str= "Visit W3School, W3School is a place to study web technology."; ; var patt=new RegExp("W3School","g"); //全局搜索"W3School" var result; while((result=patt.exec(str))!=null) //搜索到的字符串不为空 { document.write(result+"<br>"+patt.lastIndex); } </scri[t>
输出:W3School 14
W3School 24
3:javascript test()方法 //test() 方法用于检测一个字符串是否匹配某个模式.
说明:调用RegExp对象r的test方法,并为它传递字符串s,与这个表示式是等价的:
(r.exec(s)!=null)。
实例:检索W3School
<script type="text/javascript"> var str="Visit W3School"; var patt1=new RegExp("W3School");//搜索W3School var result=patt1.test(str); document.write("Result: " + result); </script> 输出:Result:true