[JS] 尋找字串中所有符合樣式的實例

var searchString = "Now is the time and this is the time and that is the time";
var pattern = /t\w*e/g;
var matchArray;

var str = "";
      
// 使用 RegExp exec 搜尋樣式,假如回傳值不是 null,則處理搜尋結果
while( (matchArray = pattern.exec(searchString)) != null ){
  str += "at " + matchArray.index + " we found " + matchArray[0] + "\n";
}
console.log(str);

以上的輸出結果為:

at 7 we found the
at 11 we found time
at 28 we found the
at 32 we found time
at 49 we found the
at 53 we found time

 

您可在此處留言

avatar

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

  Subscribe  
Notify of