Javascript 替换左括号和右括号 [英] Javascript replace opening and closing brackets

查看:116
本文介绍了Javascript 替换左括号和右括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字符串,例如

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 "]".

例如

[text1] [[text2] [text3]

应该导致

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

如何使用 Javascript 中的正则表达式来实现?

How can I accomplish that with regex in Javascript?

我是这样写的

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

但这对我的问题不起作用,它只是替换了每个括号.

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

推荐答案

您可以使用

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

详情

  • \[ - 一个 [ 字符
  • ([^\][]+) - 第 1 组:a 否定字符类匹配除 [] 之外的任何 1+ 字符(注意,在 JS 正则表达式中的字符类中,] char 必须始终被转义,即使它被放置在否定类的开头)
  • ] - 一个 ] 字符(在字符类之外,] 并不特殊,不需要转义).
  • \[ - 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).

在替换模式中,$$ 代表文字 $ 字符,{ 添加一个 { 字符, $1 插入 Group 1 值,然后添加 }.

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

这篇关于Javascript 替换左括号和右括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆