如何使用javascript正则表达式替换URL的主机部分

时间:2017-01-11 03:57:45

标签: javascript regex url

如何使用javascript regex替换网址的主机部分。这可以是带或不带http的任何类型的URL。假设此文本来自json文件的内容。

OldText:

{
   "auth" : {
     "login" : "http://local.example.com:85/auth/signin",
     "resetpass" : "http://local.example.com:85/auth/resetpass",
     "profile" : "http://local.example.com/auth/profile"
   }
}

期待像以下的解决方案:

var NewText = OldText.replace (/(some regex)/g, 'example.com');

将NewText设为:

{
  "auth" : {
     "login" : "http://example.com:85/auth/signin",
     "resetpass" : "http://example.com:85/auth/resetpass",
     "profile" : "http://example.com/auth/profile"
    }
}

我找到了相同的here,但正则表达式在javascript中无法使用。

注意:我正在寻找正则表达式。

3 个答案:

答案 0 :(得分:8)

您可以使用网址功能并设置新的主机名:

var oldUrl = "http://host1.dev.local:8000/one/two";
var url = new URL(oldUrl);
url.hostname = 'example.com';
url.href //'http://example.com:8080/one/two'

答案 1 :(得分:2)

这可以通过以下方式轻松实现:

var NewText = OldText.replace (/(https?:\/\/)(.*?)(:*)/g, '$1' + 'example.com' + '$3'); 

欢迎您使用最佳做法对其进行修改。

答案 2 :(得分:0)

我认为使用正则表达式完全可行。 这是给你的一个小片段,请告诉我你是否想要添加别的东西。

var urls = [
    {
      url: "http://local.something.com:85/auth/signin"
    }, 

    {
      url: "local.anything.com/auth/profile"
    }
];
for(var i in urls) {
  var newUrl = urls[i].url.replace(/(http:|)(^|\/\/)(.*?\/)/g, 'https://example.com/');
  console.log(newUrl);
}

我假设,来自

  

没有http

,你的意思是'google.com'