To check whether a string contains a substring in JavaScript, you can use the includes
method of the String
object.
Here’s an example of how you can use the includes
method to check whether a string contains a substring:
const str = 'Hello, World!'; if (str.includes('Hello')) { console.log('The string contains the substring.'); } else { console.log('The string does not contain the substring.'); }
This will check whether the string 'Hello, World!'
contains the substring 'Hello'
, and print the appropriate message.
Alternatively, you can use the indexOf
method of the String
object to check for the presence of a substring:
const str = 'Hello, World!'; if (str.indexOf('Hello') !== -1) { console.log('The string contains the substring.'); } else { console.log('The string does not contain the substring.'); }
This will also check whether the string 'Hello, World!'
contains the substring 'Hello'
, and print the appropriate message.
Keep in mind that both the includes
and indexOf
methods are case-sensitive, so they will not match substrings that differ in case. If you need to perform a case-insensitive search, you can use the toLowerCase
or toUpperCase
method to convert the string and the substring to the same case before checking for their presence.