I want to split on Red
and red
how can I make split case insensitive?
const str = "my Red balloon"
const searchTxt = "red"
const strArr = str.split(searchTxt);
I've tried variations of
const strArr = str.split(/searchTxt/gi);
The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.
JavaScript String Replace | Case Insensitive. The . replace function in JavaScript helps developers replace all the occurrences of a string in a text. However, many of us developers use this method in the wrong way while writing the code.
split() The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.
Use the RegExp constructor with the desired flags as second argument
RegExp(expression, flags)
Important: when passing arbitrary strings (like from a user input) to the RegExp constructor - make always sure to
escape RegExp special characters the RegExp
might confuse as regular expression tokens such as .
(any character) ?
(one or more) etc, etc. See the two link-demos below.
const str = "my Red balloon"
const searchTxt = "red"
const regEscape = v => v.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
const strArr = str.split(new RegExp(regEscape(searchTxt), "ig"));
console.log(strArr)
In order to use a variable in a regular expression, you need to use the RegExp constructor. No need to use the g
flag, since split
will always look for all occurrences:
const str = "my Red balloon"
const searchTxt = "red"
const strArr = str.split( new RegExp(searchTxt, 'i') );
console.log(strArr);
Simply put all to lower case:
const str = "my Red balloon"
const searchTxt = "red"
const strArr = str.toLowerCase().split(searchTxt.toLowerCase());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With