
In the example above, the search for the string “world” begins at index 5 of the string “Hello, world!”. The indexOf() method can also take an optional second argument, which specifies the index at which the search should begin. If the specified string is not found, the indexOf() method will return -1. The indexOf() method in JavaScript is used to search for a specified string in a given string and return the index at which the specified string is found. To learn more about the above useful string methods and how they work, make sure to read along. But this is a wonderful chance to learn JavaScript at the same. In case you found what you were looking for in the above answers, feel free to stop reading right here.

This is a comprehensive guide to checking if a string has a substring in JavaScript. Using the match() method: This method searches the string for a match against a regular expression, and returns an array containing the matched substrings, or null if no match is found. Using the search() method: This method is similar to indexOf(), but it supports regular expressions, allowing for more advanced substring matching. This method returns a boolean value indicating whether the string contains the substring or not. This method returns the index of the first occurrence of the substring in the string, or -1 if the substring is not found.įor example, let’s check if “word” exists in “Hello world!”: var str = "Hello world!" Here’s a short summary of the most notable ones. There are several ways to check if a JavaScript string contains a substring. log ( isASubstring ( "JavaScript", "Java" ) ) // true console.

function isASubstring ( largerString, smallerString ) console. However, Internet Explorer and some other old browsersĭo not support the includes() method.

Includes() method was introduced in ES6, since then it is a widely used string method. I am going to discuss two built-in methods of JavaScript string, which helps us in determining whether a string is a substring of another string or not. In this tutorial, you will learn how you can check whether a substring is included in a string or not.
