簡體   English   中英

替換屬性值的一部分

[英]replace part of attribute value

我有一個包含以下div的頁面

<div class="info" attribute-one="value one" attribute-two="value two" json="see below"></div>

“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
}

現在我想替換JSON字符串中的resource參數:

"resource": "\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",

"resource": "http:\/\/domain.com\/page\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",

但我不知道如何使用JavaScript中的正則表達式來做到這一點。 有人幫我解決這個問題嗎?

我要做的是跳過正則表達式,並解析為JSON:

var jsonObject = JSON.parse(theJsonString);
jsonObject.resource = "http://domain.com/page" + jsonObject.resource;
theJsonString = JSON.stringify(jsonObject);

你可以將theJsonString放入元素中。

你可以使用一些JQuery和JOSN函數

看看這個小提琴

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>

和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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM