indexOf()
MethodThe simplest and fastest way to check whether a string contains a substring or not in JavaScript is the indexOf()
method. This method returns the index or position of the first occurrence of substring within the string, otherwise, it returns -1 if no match found. Here is an example:
<script>
// Sample string
var str = "The quick brown fox jumps over the lazy dog."
// Check if the substring exists inside the string
var index = str.indexOf("fox");
if(index !== -1){
alert("Substring found!");
} else{
alert("Substring not found!");
}
</script>
In ES6 you can use the includes()
method to check if a contains a substring. This method simply returns true
or false
instead of the index. Let's check out an example:
<script>
// Sample string
var str = "The quick brown fox jumps over the lazy dog."
// Check if string contains substring
if(str.includes("fox")){
alert("Substring found!");
} else{
alert("Substring not found!");
}
</script>
Check out the tutorial on JavaScript ES6 features to learn about new features introduced in ES6.
Further, you can use the search()
method to search a particular piece of text or pattern (using regular expression) inside a string. Like indexOf()
method the search()
method also returns the index of the first match, and returns -1 if no matches were found.
<script>
// Sample string
var str = "Color red looks brighter than color blue."
// Search the string for a match
var index = str.search(/color/i);
if(index !== -1){
alert("Substring found!");
} else{
alert("Substring not found!");
}
</script>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel Collection count and countBy Method Example
In this article, we will discuss about h...How to find character in string php
You can use the PHP strpos() f...How to integrate Rozorpay Payment Gateway in Laravel 8
Today, I will share with you how to inte...How to replace character inside a string in JavaScript
Use the JavaScript replace() method Y...How to base64 encode and decode in Python
Base64 encoding and decoding is used whe...