雖然一直在使用正則表達式,可是一直沒有系統的概括。如下從正則表達是的功能進行相應的介紹。若有不正確的地方,望請糾正。正則表達式
模式檢測是指要檢測的文本是否符合咱們預期的模式,主要用於作登陸、註冊的驗證等:如,咱們常常在註冊時要求帳號長度爲6-16位等,如下是經常使用正則表達式spa
2. 文本內容的部分替換code
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. 得到模式匹配的文本blog
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"]