Introduction
In this lab, we will be exploring how to perform a case-insensitive substring search in JavaScript. We will use the RegExp constructor and the 'i' flag to create a regular expression that can match the given search string, ignoring the case. By the end of this lab, you will have a better understanding of how to search for substrings without having to worry about case-sensitivity.
Case-Insensitive Substring Search
To check if a string contains a substring regardless of the case, follow these steps:
- Use the
RegExpconstructor with the'i'flag to create a regular expression that matches the givensearchString, ignoring the case. - Use
RegExp.prototype.test()to check if the string contains the substring.
Here is an example code snippet:
const includesCaseInsensitive = (str, searchString) =>
new RegExp(searchString, "i").test(str);
To test this function, you can run:
includesCaseInsensitive("Blue Whale", "blue"); // true
Summary
Congratulations! You have completed the Case-Insensitive Substring Search lab. You can practice more labs in LabEx to improve your skills.