From d41d1840e51716697e7292d5711801a7ae1234cb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 27 May 2024 22:54:40 +0300 Subject: [PATCH] Questionify includes-case-insensitive --- .../snippets/js/s/includes-case-insensitive.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/content/snippets/js/s/includes-case-insensitive.md b/content/snippets/js/s/includes-case-insensitive.md index 20ad79ea0e7..6f2ea2d802f 100644 --- a/content/snippets/js/s/includes-case-insensitive.md +++ b/content/snippets/js/s/includes-case-insensitive.md @@ -1,16 +1,19 @@ --- -title: Case-insensitive substring search -type: snippet +title: Can I check if a JavaScript string contains a substring, regardless of case? +shortTitle: Case-insensitive substring search +type: question language: javascript -tags: [string] +tags: [string,regexp] cover: cup-of-orange -dateModified: 2022-07-28 +excerpt: Search for substrings in JavaScript strings without worrying about case sensitivity. +dateModified: 2024-05-25 --- -Checks if a string contains a substring, case-insensitive. +As with most languages, JavaScript's **substring matching is case-sensitive by default**. If you need to check if a string contains a substring, but you don't care about the case, you'll need to roll up your own solution. -- 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. +Converting both strings to **lowercase** before comparing them is the naive approach, but it's generally discouraged for performance reasons. Instead, you can use a **regular expression** with the `'i'` flag to perform a case-insensitive search. + +In order to do so, you'll have to use the `RegExp()` constructor to create a regular expression that matches the given `searchString`, ignoring the case. Then, you can use the `RegExp.prototype.test()` method to check if the string contains the substring. ```js const includesCaseInsensitive = (str, searchString) =>