Javascript replace opening and closing brackets

青春壹個敷衍的年華 提交于 2020-12-08 06:23:07

问题


I have a string of text, for example

[text1] [text2] [text3]

I want to replace "[" character with "${" and "]" character with "}", but only in that case, when "[" is followed up by "]".

For example

[text1] [[text2] [text3]

should result in

${text1} [${text2} ${text3}

How can I accomplish that with regex in Javascript?

I wrote something like this

someString = someString.replace(/\[/g, "${");
someString = someString.replace(/]/g, "}");

But it doesn't work for my problem, it just replaces every bracket.


回答1:


You may use

var s = "[text1] [[text2] [text3]";
console.log(s.replace(/\[([^\][]+)]/g, "$${$1}"));

Details

  • \[ - a [ char
  • ([^\][]+) - Group 1: a negated character class matching any 1+ chrs other than [ and ] (note that inside a character class in a JS regex, the ] char must always be escaped, even if it is placed at the negated class start)
  • ] - a ] char (outside of a character class, ] is not special and does not have to be escaped).

In the replacement pattern, $$ stands for a literal $ char, { adds a { char, $1 inserts the Group 1 value and then a } is added.



来源:https://stackoverflow.com/questions/52062279/javascript-replace-opening-and-closing-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!