javascript how to make a split() case insensitive

Viewed 2420

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);
3 Answers

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);

You need to use a RegExp() like this:

const str = "my Red balloon"
const searchTxt = "red"
const rgx = RegExp(searchTxt, "gi");
const strArr = str.split(searchTxt);

This is because you can't simply use the /searchTxt/gi method because it will read it as a string (so it's going to get split where it matches "searchTxt", as a string and not as a variable).

Related