How to check if a String contains substring or a word using javaScript

In order to know if a particular String contains a given word or a substring you can make use of the indexOf() method in javaScript

String.prototype.indexOf(): The indexOf method will return the index of the calling String object, it will return the first occurrence of the provided substring value. It will return -1 if the provided substring is not found.

<h2>JavaScript Substring example:</h2>
<div id="myString1">This is some text and i want to find if the work apple is in this string or not!</div>
<div id="myString2">This string does not contains that word!</div>
var val1 = document.getElementById("myString1").innerHTML.indexOf("apple");

var val2 = document.getElementById("myString2").innerHTML.indexOf("apple");

if(val1 > -1) {
  console.log("myString1 contain the word apple!");
} else {
  console.log("myString1 does not contain the word apple!")

if(val2 > -1) {
  console.log("myString2 contain the word apple!");
} else {
  console.log("myString2 does not contain the word apple!")

"myString1 contain the word apple!"
"myString2 does not contain the word apple!"

JavaScript contains substring example code
JavaScript contains substring example code
Check out jsfiddle:

Have Questions? Post them here!

Recent Posts:

Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.