I’m using a the .replace() method in javascript to convert a serialized array of objects into a simpler serialzed string. Here is my code:
b = //string
b = b.replace(/},{/gi, "},cb,,{");
b = b.replace(/}],[{/gi, "},cb,,row,{"); //The error is being thrown for this line
When I run this code I am getting an “Unexpected Token /” error for the third line. Why is this? The line is more or less identical to the line above it. Please help me figure this out.
Note: I cant submit a string without the regex as an argument because I need the substring to be replaced more than once.
In this context, the opening
[is a special character that indicates a character class. Since there isn’t a]occurring after it, the error occurs.You simply need to escape the
[for your regex to work:For the sake of consistency, I wouldn’t hesitate to escape the other brace characters since they are special characters as well (but happen to be parsed literally in this context):