【问题标题】:Replace host in all URLs in a string - nodejs替换字符串中所有 URL 中的主机 - nodejs
【发布时间】:2016-12-26 06:45:16
【问题描述】:

我有以下字符串:

{
   "auth" : {
     "login" : "http://123.123.11.22:85/auth/signin",
     "resetpass" : "http://123.123.22.33:85/auth/resetpass",
     "profile" : "http://123.123.33.44:85/auth/profile"
   }
}

我需要用我的主机名替换所有 IP 地址以获得以下输出:

{
   "auth" : {
      "login" : "http://mydomain:85/auth/signin",
      "resetpass" : "http://mydomain:85/auth/resetpass",
      "profile" : "http://mydomain:85/auth/profile"
   }
}

我可以将此字符串转换为对象、遍历属性、拆分和重新加入以形成 URL。我正在寻找使用正则表达式实现这一目标的最佳实践。

我期待类似的东西

var newUrl = text.replace( /someRegex/gi, 'mydomain');

【问题讨论】:

  • 不好但很短。 JSON.parse(JSON.stringify(thatObject).replace(/someRegex/gi, 'myDomain'))
  • 我知道如何字符串化。我需要那个正则表达式。
  • 来自谷歌搜索regextester.com/22

标签: javascript regex node.js string url


【解决方案1】:

使用((?:\d+\.){3}\d+)(?=:\d+) 并替换捕获的组对您有用。

demo here

【讨论】:

  • 像魅力一样工作。就我而言:var result = data.replace(/((?:\d+.){3}\d+)(?=:\d+)/g, host);
猜你喜欢
  • 1970-01-01
  • 2019-12-11
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
相关资源
最近更新 更多