替换所有出现的正则表达式

时间:2019-09-09 13:32:11

标签: javascript regex

我想将", ]"的所有出现替换为"]"

我尝试过:

 const str = 'website , ] asdf asdf , asdf'

 str.replace('/, ]/g',']')

什么都没发生

4 个答案:

答案 0 :(得分:0)

查找所有, ]出现的正则表达式为/, ]/g

您还应该存储replace()方法返回的新字符串。

const str = 'website , ] asdf asdf , asdf';

const result = str.replace(/, ]/g, ']');
 
console.log(result);

答案 1 :(得分:0)

您可以使用String.replace并向带有全局标志的regexp替换所有出现的内容。

使用\s任何类型的空间
使用\]来匹配]

const str = "website , ] asdf asdf , asdf";
console.log(str.replace(/,\s\]/g, "]"));

答案 2 :(得分:0)

这将起作用:

str.replace(/, ]/gm,"]");

online regex tester

code generator

答案 3 :(得分:0)

str.replace('/, ]/g',']')不会就地更改str。您必须将结果分配给另一个字符串变量:

var result = str.replace('/, ]/g',']');
console.log(result)