How do I check if a string contains a substring in JavaScript?
Benjamin C
To check if a string contains a substring in JavaScript, you can use various methods provided by the String API. Here's a step-by-step guide on how to achieve this:
1. Create a string you want to search within:
1
2
3
const string = "Hello, world!";
2. Use theincludes() method:
Theincludes() method returns a boolean value indicating whether the string contains the specified substring. It is case-sensitive.
3. Use theindexOf() method:
TheindexOf() method returns the index of the first occurrence of the specified substring within the string. If the substring is not found, it returns -1.
4. Use thesearch() method:
Thesearch() method searches for a specified substring within the string and returns the index of the first occurrence. If the substring is not found, it returns -1. Thesearch() method can also accept a regular expression.
5. Use a regular expression with thetest() method:
Thetest() method of a regular expression can be used to check if the string contains a substring that matches the regular expression pattern. It returns a boolean value.