How to check if a string contains another string in JavaScript

Checking if a string contains a word is a common task in any programming language. In JavaScript there are several ways to check whether a string contains a word or a substring.

Using the includes method

The method includes()is the official way to check if a string is contained within another string. It returns either a true or false.

‘Hi world’.includes(‘world’); // true – javascript includes string method

Note that the method includes()is case sensitive, so if you want to search for an independent string if it is uppercase or lowercase, you can do the following:

‘HI WORLD’.includes(‘world’); // false

‘HI WORLD’.toLowerCase().includes(‘world’); // true – javascript string lowercase

Read: How to delete values ​​from an array in Javascript

You can optionally pass a second parameter to indicate where to start looking for the substring:

‘AMTRACK’.includes(‘A’, 0); // true

‘AMTRACK’.includes(‘A’, 1); // false

‘AMTRACK’.includes(‘M’, 1); // true

Using the indexOf () method

Before the release of the official method includes(), another way to check if a string contains a substring was to use the method indexOf(). This method returns an integer with the position of the substring, and if it does not find the substring, it returns -1. You can also pass an optional second parameter to indicate where to start searching. See the example below:

‘amtrack’.indexOf(‘a’) !== -1 // true

‘amtrack’.indexOf(‘g’) !== -1 // false

‘amtrack’.indexOf(‘a’, 1) !== -1 // false

‘amtrack’.indexOf(‘a’); // 0 – Javascript string contains character check

‘amtrack’.indexOf(‘m’); // 1 – javascript string indexof


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Marianne elanotta

As a graduate in communication technologies, Marianne likes to share the latest technological advances in various fields. She likes to program in Java OO and Javascript and prefers to work on Open source operating systems. She likes to play chess and computer games in her spare time along with her 2 kids.

Leave a Reply