Case-Insensitive Substring Search

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28386{{"`Case-Insensitive Substring Search`"}} javascript/data_types -.-> lab-28386{{"`Case-Insensitive Substring Search`"}} javascript/arith_ops -.-> lab-28386{{"`Case-Insensitive Substring Search`"}} javascript/comp_ops -.-> lab-28386{{"`Case-Insensitive Substring Search`"}} end

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.

Other JavaScript Tutorials you may like