替换字符串和方括号不能与RegExp一起使用

艾哈迈达利波洛奇

我有一个字符串,多次出现这样的键

var str = '[a] is a string with many [a] but only one [b]';

现在我有一个对象,其键的值在str中;

var obj = {a:'the a',b:'the b'};

我试图这样用它们的值替换那些键

let output = str;
for (const key in obj) {
      output = output.replace(new RegExp('[[' + key + ']]', 'g'), obj[key]);
    }

它的输出是

[the a is a string with many [the a but only one [the b

有谁能说出我的缺失?

编辑

我怎么能代替@[a](a)the a@[b](b)the b

 var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)';
阿努巴瓦

您应该使用以下代码:

var str = '@[a](a) is a string with many @[a](a) but only one @[b](b)';
var obj = {a:'the a',b:'the b'};

let output = str;
for (const key in obj) {
   output = output.replace(new RegExp('@\\[' + key + '\\]\\(' + key + '\\)', 'g'), obj[key]);
}

console.log(output);
//=> "the a is a string with many the a but only one the b"

[必须在Javascript正则表达式中转义,并且在使用RegExp构造函数时应转义两次。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

带有real_escape_string的MySQLi不能与方括号一起使用

Python f字符串格式不能与strftime内联一起使用

带字符串键的Lua表不能与数字索引一起使用?

Unicode 字符串不能与 P/Invoke 中的 void 一起使用

C#字符串比较不能与斜杠一起使用

替换字符串中的括号和方括号

转义字符不能与innerHTML一起使用

模拟不能与pytest和flexmock一起使用

将数组元素转换为字符串不能与preg_match一起使用,即使相同的字符串也可以与相同的preg_match一起使用

解析字符串C#(可能与Regex一起使用)

symfony 4 Fixtures datetime方法不能与PDO数据中的字符串一起使用,始终设置为“ now”

无法理解为什么正则表达式不能与字符串的开始/结束标记一起使用

视图集不能与 ^ 和 $ 一起使用,并且为基数为 10 的 int() 添加了无效文字:在字符串正则表达式 django rest 框架上

为什么VBA不能在Word和Excel中将替换功能与CRLF一起使用

Ruby:使用方括号和字符串键访问字符串中的字符

React 别名不能与括号符号访问器一起使用

在方括号和非括号上分割字符串

用空字符串替换Java中方括号之间的逗号和句号

Java:替换字符串(用方括号!)

如何替换包含方括号的字符串

sed + 用键替换方括号中的字符串

用字符串中的方括号替换内容

不能使字符串相等方法和将字符串转换为数字一起工作。

在Scala中一起支持引号和字符串替换

为什么在bash 3.2中source命令不能与进程替换一起使用?

如何将curl与包含方括号字符的网址一起使用?

数据表:与j一起使用的方括号

如何使此字符串替换代码与`<br/>`标签一起使用?

为什么连字符不能与内部<span>一起使用?