How to check whether a string contains a substring in JavaScript? In JavaScript, you have numerous options for determining whether a string contains a substring. Here are a few of the most prevalent approaches: String. prototype.includes() : The includes() method determines whether a string contains a given substring and returns a boolean value (true or false). const str = 'Hello, world!'; const substring = 'world'; if (str.includes(substring)) { console.log('Substring found.'); } else { console.log('Substring not found.'); } String. prototype.indexOf() : The indexOf() method returns the first index in the string at which a substring can be found. If the substring cannot be retrieved, the function returns -1. const str = 'Hello, world!'; const substring = 'world'; if (str.indexOf(substring) !== -1) { console.log('Substring found at index ' + str.indexOf(substring)); } else { console.log('Substring not found.'); } ...
The ultimate blog for tech interview preparation!