开发者

How to remove square brackets in string using regex?

['abc','xyz'] – this string I want turn into abc,xyz using regex in javascript. I want to replace both open close square bracket & single quot开发者_高级运维e 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:

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

Be careful with eval, of course.


Just here to propose an alternative that I find more readable.

/\[|\]/g

JavaScript implementation:

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.


This should work for you.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜