0

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.

1 Answer 1

5

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:

b = b.replace(/}],\[{/gi, "},cb,,row,{");

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):

b = b.replace(/\}\],\[\{/gi, "},cb,,row,{");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.