如何使用javascript正则表达式替换URL的主机部分 [英] How to replace host part of a URL using javascript regex
本文介绍了如何使用javascript正则表达式替换URL的主机部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用javascript regex替换网址的主机部分。这可以是带或不带http的任何类型的URL。假设此文本来自json文件的内容。
How to replace the host part of a URL using javascript regex. This can be any kind of URL with or without http. Assume this text is from the content of a json file.
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设为:
To get NewText as:
{
"auth" : {
"login" : "http://example.com:85/auth/signin",
"resetpass" : "http://example.com:85/auth/resetpass",
"profile" : "http://example.com/auth/profile"
}
}
我发现了相同的这里,但该正则表达式不适用于javascript。
I found the same here, but that regex won't work in javascript.
注意:我正在寻找正则表达式。
Note: I'm looking for the Regex.
推荐答案
您可以使用URL功能并设置新的主机名:
You can use the URL function and set a new hostname:
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'
这篇关于如何使用javascript正则表达式替换URL的主机部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文