[英]replace part of attribute value
I have a page with the following div 我有一个包含以下div的页面
<div class="info" attribute-one="value one" attribute-two="value two" json="see below"></div>
The "json" attribute is filled with a compressed JSON string similar to “json”属性填充了类似于的压缩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
}
Now I want to replace the resource parameter in the JSON string, from: 现在我想替换JSON字符串中的resource参数:
"resource": "\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",
to 至
"resource": "http:\/\/domain.com\/page\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",
But I have no idea how to do this with regular expressions in JavaScript. 但我不知道如何使用JavaScript中的正则表达式来做到这一点。 Anyone kind enough to help me out with this? 有人帮我解决这个问题吗?
What i would do is skip the regex, and parse as JSON: 我要做的是跳过正则表达式,并解析为JSON:
var jsonObject = JSON.parse(theJsonString);
jsonObject.resource = "http://domain.com/page" + jsonObject.resource;
theJsonString = JSON.stringify(jsonObject);
It's up to you to put theJsonString
into the element. 你可以将theJsonString
放入元素中。
You can yse some JQuery and JOSN functions 你可以使用一些JQuery和JOSN函数
Take a look at this fiddle 看看这个小提琴
HTML: 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: 和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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.