简体   繁体   English

如何使用正则表达式删除字符串中的方括号?

[英]How to remove square brackets in string using regex?

['abc','xyz'] – this string I want turn into abc,xyz using regex in javascript. ['abc','xyz'] - 这个字符串我想在 javascript 中使用正则表达式变成abc,xyz I want to replace both open close square bracket & single quote with empty string ie "" .我想用空字符串替换左方括号和单引号,即""

Use this regular expression to match square brackets or single quotes:使用此正则表达式匹配方括号或单引号:

/[\[\]']+/g

Replace with the empty string.替换为空字符串。

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

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

here you go给你

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

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

Just here to propose an alternative that I find more readable.只是在这里提出一个我觉得更具可读性的替代方案。

/\[|\]/g

JavaScript implementation: JavaScript 实现:

let reg = /\[|\]/g

str.replace(reg,'')

As other people have shown, all you have to do is list the [ and ] characters, but because they are special characters you have to escape them with \\ .正如其他人所展示的,您所要做的就是列出[]字符,但因为它们是特殊字符,所以您必须用\\将它们转义。

I personally find the character group definition using [] to be confusing because it uses the same special character you're trying to replace.我个人认为使用[]的字符组定义令人困惑,因为它使用您要替换的相同特殊字符。

Therefore using the |因此使用| (OR) operator you can more easily distinguish the special characters in the regex from the literal characters being replaced. (OR) 运算符,您可以更轻松地将正则表达式中的特殊字符与被替换的文字字符区分开来。

This should work for you.这应该适合你。

str.replace(/[[\]]/g, "");

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

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