How do you check if a string includes a specific word value with JavaScript?
By using JavaScript’s built-in includes()
method, which determines whether a string contains the specific characters you’re looking for.
So let’s say you want to know if this HTML page contains the word “JavaScript”:
<article>
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nobis, iure eaque?
Beatae JavaScript fuga voluptatibus quae dolor odit magni voluptas iusto
illo blanditiis sed, temporibus harum minima hic quos voluptatem autem!
</p>
</article>
To find out via JavaScript, first we need to select the element we suspect contains the string value (word) we’re looking for. In this case, it’s the <article>
element:
const findJavaScriptString = document.querySelector("article").innerText
We add the innerText
property as a filter because we’re only looking for the word (string value) “JavaScript” inside human-readable elements.
If, however, you are looking for a string value inside any HTML element, including inside <script>
and <style>
elements, then we use the textContent
property instead.
Now that you have declared a variable findJavaScriptString
that references the entire <article>
element (containing the word JavaScript amongst the gibberish lorem ipsum text), let’s apply the includes()
method and print the result:
console.log(findJavaScriptString.includes("JavaScript"))
// true
If you’ve done everything correctly, your console output should say "true"
.