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.

Example:
<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>
<br/>
<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 contains the word apple!");
} else {
  console.log("myString1 does not contain the word apple!")
}

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

Output:
"myString1 contains the word apple!"
"myString2 does not contain the word apple!"

JavaScript contains substring example code
JavaScript contains substring example code
Check out jsfiddle: https://jsfiddle.net/9h3zcd0q/


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap