How to check if a string contains another string (substring) in javascript ?

Published: March 04, 2022

Updated: December 09, 2022

Tags: Javascript;

DMCA.com Protection Status

Examples of how to test if a string contains another string (substring) in javascript:

Check if a string contains another string in javascript

Let's consider the following string:

var s = 'Tokyo is the most populated city in the world'

To check for example if s contains the word 'city', a solution is to use includes():

console.log( s.includes('city') );

returns here

true

However

var word = 'Paris'

console.log( s.includes(word) );

returns

false

With a if statement

Another example with a if statement

var word = 'Tokyo';
if ( s.includes(word) ){

    console.log( `Yes, ${word} is a substraing of: "${s}"` );

}

returns

Yes, Tokyo is a substraing of: "Tokyo is the most populated city in the world"