js match函數注意


match函數

String.prototype.match

參數

regexp

返回

返回包含所有匹配的數組,如果匹配失敗返回Null。

數組第一項是整段字符串的匹配,第二項至以后都是捕獲匹配。

注意

需要注意的是:

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.

如果match函數加了/g標志位,返回的數組里只包含整段字符串的匹配。

比如

`1234567890`.match(/(\d{3})+$/)         //["234567890", "890", index: 1, input: "1234567890"]
`1234567890`.match(/(\d{3})+$/g)       //["234567890"]

解決方案

使用exec函數:

var myRe = /(\d{3})+$/g;
var str = '1234567890';
var myArray;var n = 0;
while ((myArray = myRe.exec(str))&&n<10) {
  console.log(myArray);n++;        //["234567890", "890", index: 1, input: "1234567890"];
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM