RegExp with search() method
The search() method will return a value of the index within the string of the first occurrence that matches the pattern, if no match is found then the result will return a value of -1. You can use the i flag within the regular expression to match on the pattern regardless of the case of the letters. I – case-insensitive making the pattern case-insensitive.
search() method
const txtArea = document.querySelector(‘textarea’);
const btn = document.querySelector(‘button’);
const res = document.querySelector(‘.results’);
const str1 = ‘Hello love World. I love JavaScript!’;
const reg = /love/i;
txtArea.value = str1;
btn.addEventListener(‘click’,()=>{
const str = txtArea.value;
const rep = str.search(reg);
if(rep == -1){
res.textContent = `Result ${reg} not found in the string!`;
}else{
res.textContent = `Result ${reg} found at index value ${rep}`;
}
console.log(rep);
})