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’);

‘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);

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

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

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.

Read: How to remove a property from a Javascript Object

See the example below:

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

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

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

‘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

Marianne is a graduate in communication technologies and enjoys sharing the latest technological advances across various fields. Her programming skills include Java OO and Javascript, and she prefers working on open-source operating systems. In her free time, she enjoys playing chess and computer games with her two children.

Leave a Reply