[英]How to replace host part of a URL using javascript regex
如何使用javascript正則表達式替換URL的主機部分 。 這可以是帶或不帶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"
}
}
我在這里發現了相同的內容,但正則表達式無法在javascript中運行。
注意:我正在尋找正則表達式。
您可以使用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');
歡迎您使用最佳實踐進行修改。
我認為使用正則表達式完全可行。 這是給你的一個小片段,如果你想為它添加別的東西,請告訴我。
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.