标签:
虽然一直在使用正则表达式,但是一直没有系统的归纳。以下从正则表达是的功能进行相应的介绍。如有不正确的地方,望请纠正。
模式检测是指要检测的文本是否符合我们预期的模式,主要用于做登录、注册的验证等:如,我们经常在注册时要求账号长度为6-16位等,以下是常用正则表达式
2. 文本内容的部分替换
1 var str="Our life is bright,we should cherish our life"; 2 var pattern=/life/g; 3 var result=str.replace(pattern,"future"); 4 console.log(result);
1 var str="Our life is bright,we should cherish our life"; 2 var pattern=/\b\w+\b/g; 3 var result=str.replace(pattern,function(word){ 4 return word.substring(0,1).toUpperCase()+word.substring(1); 5 }); 6 7 console.log(result);//Our Life Is Bright,We Should Cherish Our Life
3. 获得模式匹配的文本
1 var str="Our life is bright,we should cherish our life"; 2 var pattern=/li\w*/g; 3 var result=str.match(pattern); 4 console.log(result);//["life", "life"]
1 var str="Our life is bright,we should cherish our life"; 2 var pattern=/li\w*/g; 3 var result=pattern.exec(str); 4 console.log(result);//["life", index: 4, input: "Our life is bright,we should cherish our life"]
标签:
原文地址:http://www.cnblogs.com/zsblogs/p/5204178.html