[英]How to replace host part of a URL using javascript regex
How to replace the host part of a URL using javascript regex. 如何使用javascript正则表达式替换URL的主机部分 。 This can be any kind of URL with or without http.
这可以是带或不带http的任何类型的URL。 Assume this text is from the content of a json file.
假设此文本来自json文件的内容。
OldText: 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"
}
}
Expecting a solution like: 期待像这样的解决方案:
var NewText = OldText.replace (/(some regex)/g, 'example.com');
To get NewText as: 将NewText作为:
{
"auth" : {
"login" : "http://example.com:85/auth/signin",
"resetpass" : "http://example.com:85/auth/resetpass",
"profile" : "http://example.com/auth/profile"
}
}
I found the same here , but that regex won't work in javascript. 我在这里发现了相同的内容,但正则表达式无法在javascript中运行。
Note: I'm looking for the Regex. 注意:我正在寻找正则表达式。
You can use the URL function and set a new hostname: 您可以使用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'
This could be achieved easily using: 这可以通过以下方式轻松实现:
var NewText = OldText.replace (/(https?:\/\/)(.*?)(:*)/g, '$1' + 'example.com' + '$3');
You are welcome to modify this with the best practice. 欢迎您使用最佳实践进行修改。
I think this is completely doable using regex. 我认为使用正则表达式完全可行。 Here's a small snippet for you, let me know if you want to add something else to it.
这是给你的一个小片段,如果你想为它添加别的东西,请告诉我。
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); }
I am assuming, from 我假设,从
without http
没有http
, you mean something like 'google.com' ,你的意思是'google.com'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.