简体   繁体   中英

javascript how to make a 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);

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

This is the right way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM