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

Active March 04, 2022    /    Viewed 68    /    Comments 0    /    Edit


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"

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount