Bill
Bill

Reputation: 5150

How to make split() case insensitive

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

Answers (4)

DadiBit
DadiBit

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

Ast
Ast

Reputation: 371

This is the right way

const str = "my Red balloon";
var arr = str.split(/red/i);

Upvotes: -1

Roko C. Buljan
Roko C. Buljan

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

blex
blex

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

Related Questions