javascriptecmascript-4

How to check if a particular string is in the innerhtml or not?


Let's assume here has a bunch of html like this:

<p>High noon</p>
<p>Highest rank!</p>

Using the querySelectorAll to get them all:

const pList = document.querySelectorAll("p");

Then I want to know does the string "high" exist in each node in ES4.


I tried both includes() and indexOf():

pList[0].innerHTML.includes("High")
pList[1].innerHTML.includes("High")
//or
pList[0].innerHTML.indexOf("High") !== -1
pList[1].innerHTML.indexOf("High") !== -1

But what I got are all true for all the nodes, rather than true for pList[0] and false for pList[1].


Solution

  • Try this one. Solution based on regular expression.

    var regex = /\bHigh\b/i;
    regex.test(pList[0]);
    regex.test(pList[1]);
    //or
    pList[0].innerHTML.search(regex) !== -1
    pList[1].innerHTML.search(regex) !== -1