In this post, we will discuss the ways in Javascript on how to check if a string contains other substring or not.
There are multiple ways to check if a string contains substring or not, but if we’re using vanilla Javascript and not using any other library or package then we can use the following two methods:
includes()
The includes()
Javascript method return boolean value as true if the substring is found else false is returned.
<script>
var myLargeText = "I very long string to find a small string out of it quickly";
console.log(myLargeText.includes('small')); // OUTPUT true
</script>
The only con of using includes() is, it is available on latest browsers
If you want to use a script in order browsers then you can opt for indexOf()
method.
indexOf()
As the name sounds, this method is actually used to find the starting index of a substring in the text string. You can use the indexOf()
method as shown below to check if a string is a substring.
var myLargeText = "I very long string to find a small string out of it quickly";
console.log(myLargeText.indexOf('small')> -1); // OUTPUT true
or you can create a reusable function as shown below
<script>
var myLargeText = "I very long string to find a small string out of it quickly";
console.log(isFound(myLargeText,'small')); // OUTPUT true
function isFound(myLargeText,substring){
return (myLargeText.indexOf(substring)> -1);
}
</script>