【问题标题】:replace part of attribute value替换部分属性值
【发布时间】:2014-12-16 19:04:51
【问题描述】:

我有一个包含以下 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": "\/session\/bc7d2c28-90d9-4b2d-97f8-a455b28c4e7d\/",

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

但我不知道如何在 JavaScript 中使用正则表达式来做到这一点。有好心人帮我解决这个问题吗?

【问题讨论】:

    标签: javascript html regex json replace


    【解决方案1】:

    我会做的是跳过正则表达式,并解析为 JSON:

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

    您可以将theJsonString 放入元素中。

    【讨论】:

    • 我会发布相同的答案:D
    【解决方案2】:

    您可以使用一些 JQuery 和 JOSN 函数

    Take a look at this fiddle

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2012-05-08
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多