In JavaScript, you can check whether a string contains another string using the includes()
or indexOf()
method. The includes()
method returns a Boolean value indicating whether the specified string is found within the calling string.
And the indexOf()
method returns the index of the first occurrence of the specified string within the calling string, or -1 if the string is not found.
JavaScript string contains example
Simple example code check if a string contains another string using the includes()
method.
<!DOCTYPE html>
<html>
<head>
<script>
const str = 'Hello, world!';
const subStr = 'world';
if (str.includes(subStr)) {
console.log('The string contains the substring');
} else {
console.log('The string does not contain the substring');
}
</script>
</head>
<body>
</body>
</html>
Output:
You can also use the indexOf()
method to check if a string contains another string.
const str = 'Hello, world!';
const subStr = 'world';
if (str.indexOf(subStr) !== -1) {
console.log('The string contains the substring');
} else {
console.log('The string does not contain the substring');
}
The javaScript string contains case insensitive
You can convert both the string and the substring to either lowercase or uppercase using the toLowerCase()
or toUpperCase()
method, and then use the includes()
or indexOf()
method to perform the check.
const str = 'Hello, world!';
const subStr = 'WORLD';
if (str.toLowerCase().includes(subStr.toLowerCase())) {
console.log('The string contains the substring (case-insensitive)');
} else {
console.log('The string does not contain the substring (case-insensitive)');
}
Do comment if you have any doubts or suggestions on this Js string topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version