Reputation: 5150
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);
Upvotes: 9
Views: 7125
Reputation: 811
You need to use a RegExp()
like this:
var str = "my Red balloon"
var searchTxt = "red"
var rgx = RegExp(searchTxt, "gi");
var strArr = str.split(rgx);
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).
Upvotes: -1
Reputation: 371
This is the right way
const str = "my Red balloon";
var arr = str.split(/red/i);
Upvotes: -1
Reputation: 206121
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)
Upvotes: 13
Reputation: 25634
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);
Upvotes: 5