Comment vérifier si une chaîne de caractères (string) contient une autre chaîne de caractères (sous-chaîne) en javascript:
Vérifier si un string contient une autre string en javascript
Considérons la chaîne de caractères suivante :
var s = 'Tokyo is the most populated city in the world'
Pour vérifier par exemple si s contient le mot 'ville', une solution consiste à utiliser includes():
console.log( s.includes('city') );
donne ici
true
Cependant
var word = 'Paris'console.log( s.includes(word) );
donne
false
Avec une instruction if
Un autre exemple avec une instruction if
var word = 'Tokyo';if ( s.includes(word) ){console.log( `Yes, ${word} is a substraing of: "${s}"` );}
donne
Yes, Tokyo is a substraing of: "Tokyo is the most populated city in the world"
