从Javascript中的字符串替换每个匹配项的字符集[重复](Replace set of characters of every occurrence from a string in Javascript [duplicate])

这个问题在这里已经有了答案:

如何在JavaScript中替换所有出现的字符串? 41个答案

在javascript中我有一些愚蠢的问题,我很接近用一个字符替换字符串中的一组字符,但无法完成。

这是代码

var mystring ="[[{"id":27,"av":20}],[{"id":24,"av":20}],[{"id":28,"av":40}]]"; mystring = mystring.replace('],[', ',');

这将取代第一次出现的给定字符'],['用','结果如此

"[[{"id":27,"av":20},{"id":24,"av":20}],[{"id":28,"av":40}]]"

我错过了什么,我怎样才能替换'],['与',''的每一处出现?

This question already has an answer here:

How to replace all occurrences of a string? 56 answers

I have some silly issue in javascript, am so close in replacing set of characters from a string with a character, but couldn't make it completely.

Here is the code

var mystring ="[[{"id":27,"av":20}],[{"id":24,"av":20}],[{"id":28,"av":40}]]"; mystring = mystring.replace('],[', ',');

This is replacing the first occurrence of the given characters '],[' with ',' so the result is

"[[{"id":27,"av":20},{"id":24,"av":20}],[{"id":28,"av":40}]]"

What am I missing, how can I replace every occurrence of '],[' with ',' ?

最满意答案

你需要用'g修饰符'来使用regex来执行全局替换:

mystring = mystring.replace(/\],\[/g, ',');

You need to use regex with the 'g modifier' to perform a global replacement:

mystring = mystring.replace(/\],\[/g, ',');

更多推荐