最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript replace opening and closing brackets - Stack Overflow

programmeradmin0浏览0评论

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 acplish 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.

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 acplish 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.

Share Improve this question edited Aug 28, 2018 at 16:17 epascarello 208k20 gold badges205 silver badges244 bronze badges asked Aug 28, 2018 at 16:14 qazerty23qazerty23 4912 gold badges6 silver badges17 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 14

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.

发布评论

评论列表(0)

  1. 暂无评论