1

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 ',' ?

Satheesh Panduga
  • 818
  • 2
  • 13
  • 32
  • Your string is a syntax error. That said, modifying JSON with string operations is probably not the best way to do things. – Pointy Jan 15 '16 at 14:26

2 Answers2

3

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

mystring = mystring.replace(/\],\[/g, ',');
R.Costa
  • 1,395
  • 9
  • 16
2

Could use split and join:

mystring.split('],[').join(',');

Not sure how it compares performance wise though.

James Coyle
  • 9,922
  • 1
  • 40
  • 48