The JavaScript indexOf()
method search for the substring in string and returns the position of the first occurrence of a specified substring. If substring not found, it returns -1. So you can use JavaScript IndexOf() method to check if a string contains substring in it. In this tutorial we will also provides example to use JavaScript includes()
and search()
methods to find substring in another string.
In a comparison of all 3 methods describes below, indexOf() can be better due to its speed of execution. If no speed matters, you can use any of the following methods.
Using indexOf() Method
JavaScript indexOf() method will return the starting position number substring in the main string. If substring not found, it will return -1 as a result.
1 2 3 4 | var str = "Hello world"; var substr = "World"; var result = str.indexOf(substr) > -1; alert(result); |
Result will be as below:
true
2. Using includes() Method:
Also you could use JavaScript includes() method. It returns true
on match found and false
if no match found. Use below sample code to test this:
1 2 3 4 | var str = "Hello world"; var substr = "World"; var result = str.includes(substr) > -1; alert(result); |
Result will be as below:
true
3: Using search() Method
You could also use the JavaScript search() method. It returns string position number if match found. If not match found returns -1.
1 2 3 4 | var str = "Hello World"; var expr = "/World/"; var result = str.search(expr) > -1; alert(result); |
Result will be as below:
true
3 Comments
also var expr = “/World/”; is written incorrectly.
it should have been written var expr = /World/; to achieve the expected results
var result = str.includes(substr) > -1; is written wrong… will return also true when substr is not in str, as false > -1 evaluates to true!!
should have been written
var result = str.includes(substr); // result will return true if substr in str, and will return false if not
You can also very easily do this by using this code, implemented in modernizr lib:
function contains(str, substr) {
return !!~(” + str).indexOf(substr);
}
U can see the full text, docs, usage examples and more at cocycles: