首页 > 代码库 > JavaScript学习笔记(三)

JavaScript学习笔记(三)

//==RegExp===
//1.正则表达式的test()方法
var result;var str = "bcatasdsrtophe" ;var re11 = /cat/g; //匹配catresult = re11.test(str);var re12 = new RegExp("Cat","gi"); //匹配cat不区分大小写result = re12.test(str);var re31 = new RegExp(".he$"); //以he结尾的字符串result = re31.test(str);alert(result);

text = "000-01-2131";
var pattern41 = /\d{3}-\d{2}-\d{4}/;
if(pattern41.test(text)){
alert("The Pattern was matched.");
}

 
//2.正则表达式exec()方法
var
text = "mom and dad and baby";var pattern = /mom( and dad( and)?)?/gi;var matches = pattern.exec(text);alert(matches); //mom and dad and,and dad and,and

//input 与 index属性
var text = "cat,bat,sat,fat";var pattern1 = /.at/;var matches = pattern1.exec(text);alert(matches); //catalert(matches.index); //0;index属性,匹配项在字符创中的位置alert(matches[0]); //catalert(matches.input); //cat,bat,sat,fat;input属性,应用正则表达式的字符串alert(pattern1.lastIndex); //0

Pattern的全局模式与非全局模式

var text= "cat,bat,fat,sat";var pattern2 = /.at/g; //全局模式var matches;for(var i=0;i<4;i++){matches = pattern2.exec(text);alert(matches+" "+pattern2.lastIndex); }//当使用了全局模式,每次调用exec()都会返回字符串中的下一个匹配项,直至搜索到字符串末尾为止。//而且在全局模式下,模式的lastIndex属性在每次调用exec()后都会增加,而在非全局模式下则始终保持不变。

 

 

JavaScript学习笔记(三)