【问题标题】:Is there a way to replace text from a JSON object after it has been stringified?有没有办法在字符串化后替换 JSON 对象中的文本?
【发布时间】:2019-07-26 23:56:08
【问题描述】:

我有一些 JSON 数据,其中包含一些 url。我通过遍历工作正常的对象从 json 中提取这些 url。但是,网址前面有“页面:”,我试图用“https://”替换。

我无法让 replace 属性工作并每次都给我相同的结果。

我已经尝试以不同的方式使用 replace() 属性,并且正在使用 console.log 来查看我的结果。我还尝试对 JSON 进行字符串化,因为我听说这是处理它的一件好事。

每次我仍然看到 'page:' 字并且它没有被替换。

function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);    
console.log(getEntries);

    for (var i = 0; i < getEntries.length; i++) {

        var list = document.createElement('article');
        var articleTitle = document.createElement('li');
        var articleUrl = document.createElement('a');
        articleTitle.textContent = getEntries[i].title.$t;
        articleUrl.textContent = getEntries[i].content.$t;

        articleUrl.textContent.replace("page: ", "https://");
        console.log(articleUrl.textContent);

    list.appendChild(articleTitle)+list.appendChild(articleUrl);
    section.appendChild(list);

    }

}

我希望输出 url 是 'https://www.google.com' 但我看到的是 'page : www.google.com'

【问题讨论】:

    标签: javascript json stringify


    【解决方案1】:

    replace()返回一个修改后的值,它不修改原始字符串。

    你想要这样的东西:

    articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2023-02-26
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多