chris
chris

Reputation: 36957

Javascript JSON Object replace string within object

Ok, I have a large multidimensional JSON object being poured into my app, of which one of the objects is an html string, for creating links. Now I have no ability to change the output of this Object currently to replace what I want to with what I need to because this object is used in a couple places through out a few different applications. Of which works fine up til now.

What I need to do is replace a small piece of this html string in the JSON object to alter it so it fits the needs of this new application.

The HTML within the object looks like (taken directly from firebug console under "response tab" less the whole object data)

<a href='\/ng\/other\/?object_id=6bfb00fb-2b76'>Some Text<\/a>

What I need to do is replace the "ng" and "other" within that string to something else entirely. To which I have tried.

var swapVal1 = data.rows[index1].vals[1].replace(\/ng\/other\/,"/new/placement/");

However I get SyntaxError: illegal character Line 31 and its pointing to the first piece of the replace function. So, what is it I would need to do, in order to handle this properly for the time being until other things can be rewritten on the back end as a better alternative to this problem.

Upvotes: 0

Views: 2901

Answers (1)

Vivin Paliath
Vivin Paliath

Reputation: 95588

Your regex is malformed. Try this:

var swapVal1 = data.rows[index1].vals[1].replace(/\\\/ng\\\/other\\\//, "/new/placement/");

Regex literals are bounded by the / character. The backslash character, \, is used to escape regex metacharacters, and so needs to be escaped to \\. Since the / character is used to denote the start and end of a regex literal, it also needs to be escaped to \/. So you can break the regex down to this:

/     -> start of regex
\\    -> the first \
\/    -> the next /
ng    -> the string "ng"
\\    -> the next \
\/    -> the / after that
other -> the string "other"
\\    -> the next \
\/    -> the / after that
/     -> end of the regex

Upvotes: 4

Related Questions