javascript - 将字符串中的双引号替换为坟墓,而不创建新字符串

标签 javascript json regex

我有一个 json,其中存储带有链接的属性。我想将其写入 .txt 文件,以便我可以复制内容并在资源对象中使用它,该资源对象具有我想使用 template literals 注入(inject)的 serverUrl 变量。 。在执行此操作之前,我需要稍微更改 JSON 的字符串值,以便可以使用模板文字。

json 对象具有以下格式:

{
  "products": [
    {
      "image": "http://test.test.com/images/imageName.jpg"
    },
    {
      "image": "http://test.test.com/images/imageName2.jpg"
    }
  ]
}

我想要实现的目标是将每个产品对象的每个图像值更改为以下格式:

`http://${serverUrl}/images/imagename`

我在 json 创建过程中设法使用简单的 string.replace() 替换了 url,但我在执行以下步骤时遇到了困难:

  1. 将双引号更改为坟墓 (""=> ``) 并保留网址。
  2. 全局执行,我不想提取值,应该覆盖该对象。

我尝试编写一些正则表达式,但我似乎无法弄清楚如何替换双引号并将网址保留在一个正则表达式中。 这是解决这个问题的正确方法吗?或者我应该尝试一些完全不同的东西

编辑

到目前为止我的代码

let dataImport = [];

// Code to convert excel to JSON
// Contains the following line for the image property
case "image": 
  value = value.replace("https://test.test.com", "${serverUrl}");
  rowData["image"] = value;
break;

// Convert object
let json = JSON.stringify(dataImport, null, 2);
fs.writeFileSync("data.txt", json);

最佳答案

var json = JSON.stringify({
  "products": [
    {
      "image": "http://test.test.com/images/imageName.jpg"
    },
    {
      "image": "http://test.test.com/images/imageName2.jpg"
    }
  ]
}, null, '  ');

var domain = "test.test.com";
console.log(convertJsonUrls(json, domain));

/**
 * Converts any strings containing urls for the specified domain into template-strings,
 * and replaces the domain with '${serverUrl}'
 */
function convertJsonUrls(json, domain) {
    var stringRE = /"((?:\\.|[^\\"])*)"/g;
    var urlRE = new RegExp("^(https?://)" + escapeRegExp(domain) + "(/.*)$");

    var template = json.replace(stringRE, function (raw, content) {
        var urlMatch = urlRE.exec(content);
        if (!urlMatch) return raw; // no change, keep double-quotes
        return "`" + urlMatch[1] + "${serverUrl}" + urlMatch[2] + "`";
    });

    return template;
}

/**
 * Escapes any RegExp special characters.
 * Copied from https://stackoverflow.com/a/6969486/22364
 */
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

关于javascript - 将字符串中的双引号替换为坟墓,而不创建新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396302/

相关文章:

javascript - 如何从特定语言的下拉列表中删除 "powered by google translate"并通过谷歌翻译器翻译网页

php - 将测验替代项保存为 JSON 字符串或单独的行?

java - 由 : java. util.regex.PatternSyntaxException 引起:非法重复

javascript - 多个 JSON 文件调用

javascript - 如何使用 jquery 显示返回的 JSON 数组

python - 将多行 make-line 变量赋值与 python 正则表达式相匹配

java - Hibernate Annotation 中的多重模式匹配

javascript - 使用CSS从div悬停的左侧推送背景颜色

javascript - 如何从 JavaScript 中的字符串数组中删除字符模式?

javascript - react / react Hook : onChange function to change text is changing for all 3 elements simultaneously instead of just one