如何使用javascript regex替换URL的主机部分。这可以是任何类型的带有或不带有http的URL。假设此文本来自json文件的内容。
旧文本:
{
"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"
}
}
我在这里找到了同样的东西,但regex在javascript中不起作用。
注意:我在找Regex。
您可以使用URL函数并设置一个新的主机名:
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'
这可以使用轻松实现
var NewText = OldText.replace (/(https?://)(.*?)(:*)/g, '$1' + 'example.com' + '$3');
欢迎您使用最佳实践对此进行修改。
我认为使用regex是完全可行的。这里有一个小片段给你,如果你想添加其他内容,请告诉我。
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">