Javascript 如何使用正则表达式删除字符串中的方括号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3812055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove square brackets in string using regex?
提问by Mugdha
['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,xyz
在 javascript 中使用正则表达式。我想用空字符串 ie 替换开闭方括号和单引号""
。
回答by Mark Byers
Use this regular expression to match square brackets or single quotes:
使用此正则表达式匹配方括号或单引号:
/[\[\]']+/g
Replace with the empty string.
替换为空字符串。
"['abc','xyz']".replace(/[\[\]']+/g,'')
回答by ithkuil
str.replace(/[[\]]/g,'')
str.replace(/[[\]]/g,'')
回答by Fourier
here you go
干得好
var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'
回答by Greg Hewgill
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
当然要小心。