日期:2014-05-16 浏览次数:20430 次
?
js正则函数match、exec、test、search、replace、split使用介绍集合,学习正则表达式的朋友可以参考下
?
stringObj.match(rgExp) 
function auth(){
    var s = "The rain in Spain falls mainly in the plain";
    re = /(a)in/ig;          // 创建正则表达式模式。
     r = s.match(re); // 尝试去匹配搜索字符串
     document.write(r);
     
}
输出结果:ain,ain,ain,ain 
rgExp.exec(str)
返回数组包含: 
input:整个被查找的字符串的值; 
index:匹配结果所在的位置(位); 
lastInput:下一次匹配结果的位置; 
arr:结果值,arr[0]全匹配结果,arr[1,2...]为表达式内()的子匹配,由左至右为1,2...。
 例:
function Test(){ 
var src="http://sumsung753.blog.163.com/blog/I love you!"; 
var re = /\w+/g;    // 注意g将全文匹配,不加将永远只返回第一个匹配。 
var arr; 
while((arr = re.exec(src)) !=null){ //exec使arr返回匹配的第一个,while循环一次将使re在g作用寻找下一个匹配。 
document.write(arr.index + "-" + arr.lastIndex + ":" + arr + "<br/>"); 
for(key in arr){ 
document.write(key + "=>" + arr[key] + "<br/>"); 
} 
document.write("<br/>"); 
} 
} 
window.onload = RegExpTest(); 
 返回结果:
0-1:I //0为index,i所在位置,1为下一个匹配所在位置 
input=>I love you! 
index=>0 
lastIndex=>1 
0=>I 
2-6:love 
input=>I love you! 
index=>2 
lastIndex=>6 
0=>love 
7-10:you 
input=>I love you! 
index=>7 
lastIndex=>10 
0=>you
?
?
注意:test()继承正则表达式的lastIndex属性,表达式在匹配全局标志g的时候须注意。?
例子5:?