Categories
JavaScript JavaScript Basics

How to Check If a JavaScript String Contains a Substring

Spread the love

Checking if a JavaScript string contains a substring is easy. We can either use the includes method or we can use the indexOf method.

includes

To use the includes method, we can do that by writing the following code:

const hasFoo = 'foo bar'.includes('foo');

In the code above, we called the includes method on the string literal. It takes the substring to seacrh for in the first argument.

The 2nd argument, which is optional, is the position in the string to start the search from.

It returns true if the substring is found in the string that it’s called on and false otherwise.

In our example, we skipped the 2nd argument, so it’ll start searching from the beginning.

Therefore, hasFoo is true since 'foo' is in the string.

To search from a given index of the string that it’s called on, we can call it as follows:

const hasFoo = 'foo bar'.includes('foo', 5);

In the code above, it’ll start searching from index 5, which is past where 'foo' is. Therefore, it’ll return false and hasFoo is false.

indexOf

indexOf is another method that we can use to check if a substring is in a string. It takes the same arguments as includes but it returns the index of the first instance of the substring. If the substring isn’t found, then -1 is returned.

We can use it as follows:

const index = 'foo bar'.indexOf('foo');

We search for the 'foo' substring in the code above. Then indexOf returns 0 since 'foo' is at the beginning of the string.

Also, we can set the index to start searching from as follows:

const index= 'foo bar'.indexOf('foo', 5);

Then we get -1 for index since 'foo' is not found in any index from 5 or beyond.

Conclusion

We can call includes and index to check if a JavaScript string contains a given substring.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *