如何使用regex删除字符串中的方括号?

时间:2022-09-15 16:00:54

['abc','xyz'] – this string I want turn into abc,xyz using regex in javascript. I want to replace both open close square bracket & single quote with empty string ie "".

['abc','xyz'] -这个字符串我想要变成abc,在javascript中使用regex。我想用空字符串ie "来替换左右括号和单引号。

4 个解决方案

#1


48  

Use this regular expression to match square brackets or single quotes:

使用此正则表达式匹配方括号或单引号:

/[\[\]']+/g

Replace with the empty string.

用空字符串替换。

"['abc','xyz']".replace(/[\[\]']+/g,'')

#2


8  

str.replace(/[[\]]/g,'')

str.replace(/[[\]]/ g,”)

#3


7  

here you go

在这里你去

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

#4


4  

You probably don't even need string substitution for that. If your original string is JSON, try:

你甚至不需要字符串替换。如果您的原始字符串是JSON,请尝试:

js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz

Be careful with eval, of course.

当然,要小心使用eval。

#1


48  

Use this regular expression to match square brackets or single quotes:

使用此正则表达式匹配方括号或单引号:

/[\[\]']+/g

Replace with the empty string.

用空字符串替换。

"['abc','xyz']".replace(/[\[\]']+/g,'')

#2


8  

str.replace(/[[\]]/g,'')

str.replace(/[[\]]/ g,”)

#3


7  

here you go

在这里你去

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

#4


4  

You probably don't even need string substitution for that. If your original string is JSON, try:

你甚至不需要字符串替换。如果您的原始字符串是JSON,请尝试:

js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz

Be careful with eval, of course.

当然,要小心使用eval。