Image

How to check if a string contains a substring in JavaScript?

To check if string contains substring in javascript you can use includes() and indexOf() Method.
1.ES6 introduce includes() method to check if a contains a substring. This method returns true if the string contains the characters, and false if not.
Note: The includes() method is case sensitive.
Note: The includes() method is not supported in IE 11 (and earlier versions).

<!DOCTYPE html>
<html>
<body>
<script>
// string
var str = "Welcome to coderuck."

// Check if string contains substring
if(str.includes("coderuck")){
    alert("found!");
} else{
    alert("Not found!");
}
</script>
</body>
</html>

2.indexOf() Method
The indexOf() method returns the position of the first occurrence of a specified value in a string.This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.

<!DOCTYPE html>
<html>
<body>
<script>
// string
var str = "Welcome to coderuck."
if(str.indexOf("coderuck")!==-1){
	alert("Found.")
}else{
	alert("Not found.")
}
</script>
</body>
</html>

 

Categories: Java Script Tags: #ES6, #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.