tonym tonym - 28 days ago 5
Javascript Question

JS Combining RegEx with While Loop

Trying to search for specific text and check if it exists in the line. If it does Display "Yes", if no then display "No".

Currently what I have:

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>`);
});
}

Answer

Try this:

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

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