CLOSE
How to use JavaScript to find a substring inside a string.
Let’s assume we have a secret passcode yacine and want to check if it exists in another string.
Here we’ll use findme to demonstrate the string we want to check:
const passcode = "yacine";
const findme = `8sowl0xeyacinexjwo98w`;
Visually we can see that findme contains yacine but how do we get a yes/no answer in JavaScript?
We can introduce a new feature in ES6, the String.prototype.includes method, which will return us a Boolean value based on whether the substring was found:
const found = findme.includes(passcode);
// true
console.log(found);
const index = findme.indexOf(passcode);
// true
const passcode = "yacine";
const findme = `8sowl0xe${passcode}xjwo98w`;
// ES6 String.prototype.includes
console.log(findme.includes(passcode));
// String.prototype.indexOf
console.log(findme.indexOf(passcode) !== -1);
const index = findme.indexOf(passcode);
// true
console.log(!!~index);
Thanks for reading!