简体   繁体   English

javascript 如何使 split() 不区分大小写

[英]javascript how to make a split() case insensitive

I want to split on Red and red how can I make split case insensitive?我想在Redred上拆分如何使拆分不区分大小写?

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构造函数作为第二个参数

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 .重要提示:当将任意字符串(如来自用户输入)传递给 RegExp 构造函数时 - 始终确保转义 RegExp 特殊字符RegExp可能会混淆为正则表达式标记,例如. ( 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.为了在正则表达式中使用变量,您需要使用 RegExp 构造函数。 No need to use the g flag, since split will always look for all occurrences:无需使用g标志,因为split将始终查找所有出现:

 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:您需要像这样使用RegExp()

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).这是因为您不能简单地使用/searchTxt/gi方法,因为它会将其作为字符串读取(因此它将在匹配“searchTxt”的地方被拆分,作为字符串而不是变量)。

This is the right way这是正确的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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