Case-Insensitive Substring Search

Beginner

This tutorial is from open-source community. Access the source code

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.

To check if a string contains a substring regardless of the case, follow these steps:

  • Use the RegExp constructor with the 'i' flag to create a regular expression that matches the given searchString, 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.