2016-11-11 20 views
-1

試圖搜索特定文本並檢查它是否存在於該行中。如果確實顯示「是」,如果否,則顯示「否」。JS將RegEx與While循環結合使用

目前我有:

const str = `Hello my name is Stack Overlow.` 
const publish = /Hello/g; 
    let pub; 
    while ((pub = publish.exec(str)) !== null) { 
     if (pub.index === publish.lastIndex) { 
      publish.lastIndex++; 
     } 
     pub.forEach((ko, groupIndex) => { 
      document.write(`"Exists": "${ko}",<br>`); 
     }); 
    } 
+1

沒問題。另外,代碼中的「是」和「否」在哪裏? – trincot

回答

1

試試這個:

var string = 'Hello my name is not important'; 
 
var pattern = /Hello/g; 
 

 
if(pattern.test(string)) { 
 
    console.log('yes'); 
 
} 
 
else { 
 
    console.log('no'); 
 
}

0

您還可以,如果你不是特別熱衷於正則表達式做到這一點與indexOf()

const str = 'Hello my name is Stack Overlow.' 
 
const containsSubstring = (string, substring) => ~string.indexOf(substring) ? 'Yes' : 'No'; 
 

 
console.log(containsSubstring(str, 'Hello')); // 'Yes'

我還包裹在一個匿名函數containsSubstring檢查。如果您稍後嘗試檢查其他子字符串,這將避免重複,因爲您可以使用任何字符串/子字符串對調用containsSubstring,而無需重寫代碼或重複自己。