how to check string contains substring using indexOf and includes method in JavaScript


Method 1 - Find out string contains substring in JavaScript using indexOf(string) method in JavaScript>

indexOf(string) - Returns the index of the first occurrence of the specified substring in string.
If string does not contains substring method simply returns -1.


What about finding index of string from specified index?
indexOf(string, int) - Returns the index of the first occurrence of the specified substring in string from specified index.
If string does not contains substring from specified index method simply returns -1.

<html>
<head>
<script type="text/javascript">
var str = "java made so easy made";
if(str.indexOf("made") != -1){
alert('str contains substring at index = '+ str.indexOf("made"));
}
else{
alert("str doesn't contains substring");
}
if(str.indexOf("made", 10) != -1){
alert('str contains substring at index = '+ str.indexOf("made", 10));
}
else{
alert("str doesn't contains substring");
}
</script>
</head>
<body>
</body>
</html>

Executing above javascript will display following alerts >
str contains substring at index = 5
str contains substring at index = 18



In above program indexOf(string, int) will start searching ‘made’ from 10th index ‘s’ (i.e. in ‘so easy’ only)


Method 2> Program to find out string contains substring in JavaScript using includes(string) method in JavaScript>


includes(string) - contains method Returns true if and only if string contains the specified string. If string does not contains substring method simply returns false.

What about finding index of string from specified index?
includes(string, int) - contains method Returns true if and only if string contains the specified string from specified index. If string does not contains substring method simply returns false.
<html>
<head>
<script type="text/javascript">
var str = "java made so easy made";
if(str.includes("made")){
alert('str contains substring');
}
else{
alert("str doesn't contains substring");
}
if(str.includes("made", 10)){
alert('str contains substring');
}
else{
alert("str doesn't contains substring");
}
if(str.includes("hi")){
alert('str contains substring');
}
else{
alert("str doesn't contains substring");
}
</script>
</head>
<body>
</body>
</html>

Executing above javascript will display following alerts >
str contains substring
str contains substring
str doesn't contains substring


In above program contains(string, int) will start searching ‘made’ from 10th index ‘s’ (i.e. in ‘so easy’ only)
Labels: JavaScript
eEdit
Must read for you :