Replace part of an attribute value
I have a page with the following div
<div class="info" attribute-one="value one" attribute-two="value two" json="see below"></div>
The json attribute is populated with a compressed JSON string like
{
"serviceContext": "\/",
"state": "READY",
"url": "http://domain.com/some-url.extension",
"zoomedPageWidth": 768,
"hits": [
],
"httpContentLoaded": 0,
"resource": "\/session\/zc7d2c08-90d8-4b2d-97f8-a455b28c4e7d\/",
"httpContentLength": 660032
}
Now I want to replace the resource parameter in the JSON string, from:
"resource": "\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",
to
"resource": "http:\/\/domain.com\/page\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",
But I don't know how to do this with regular expressions in JavaScript. Anyone enough to help me with this?
+3
Dylan
source
to share
2 answers
What I would do is skip the regex and parse as JSON:
var jsonObject = JSON.parse(theJsonString);
jsonObject.resource = "http://domain.com/page" + jsonObject.resource;
theJsonString = JSON.stringify(jsonObject);
You need to put theJsonString
in an element.
+4
Scimonster
source
to share
You can use some JQuery and JOSN functions
Look at this violin
HTML:
<div id="test" json='{"serviceContext": "\/", "state": "READY","url": "http://domain.com/some-url.extension","zoomedPageWidth": 768,"hits": [],"httpContentLoaded": 0,"resource":"\/session\/zc7d2c08-90d8-4b2d-97f8-a455b28c4e7d\/","httpContentLength": 660032}'></div>
and JS:
var testElement = $('#test'),
a = testElement.attr('json');
o = JSON.parse(a);
o.resource = 'http://domain.com/page/session' + o.resource;
testElement.attr('json', JSON.stringify(o));
0
Piotr W
source
to share