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 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!")
}

Output:
"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: https://jsfiddle.net/9h3zcd0q/
Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


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, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency