比如我有一個像網址: ftp://xxx:[email protected]/BigFile.zip如何從FTP地址獲取基址?
如何使用javascript/jQuery的我得到example.com從這個網址?
比如我有一個像網址: ftp://xxx:[email protected]/BigFile.zip如何從FTP地址獲取基址?
如何使用javascript/jQuery的我得到example.com從這個網址?
你可以瀏覽你喜歡這個解析的網址:
var a = document.createElement('a');
a.href = 'ftp://xxx:[email protected]/BigFile.zip';
var host = a.hostname;
,讓你的主機名,在這種情況下會ftp.example.com
,如果由於某種原因,你必須刪除子域,你可以做
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
這裏的不同部分的URL - >https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
下面是使用JavaScript RegExp
input = "ftp://xxx:[email protected]/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\[email protected]\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
您還可以使用i
在表達式的末尾,使其不區分大小寫。
pattern = new RegExp(/ftp:\/\/\[email protected]\S+?\.([^\/]+)/i);
您可以使用jQuery這樣的:
var url = "ftp://xxx:[email protected]/BigFile.zip";
var ahref = $('<a>', { href:url })[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
你可以有一個正則表達式來爲你做這個。
url = 'ftp://xxx:[email protected]/BigFile.zip'
base_address = url.match(/@.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
雖然這將包含ftp.example.com
。您可以根據需要對其進行微調。
我只是想嘗試/添加不同的東西(性能或通用的解決方案可以不賭,但它的作品,哎,而不涉及DOM /正則表達式!):
var x="ftp://xxx:[email protected]/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
對於給定的情況下,可以是最短的,因爲始終將 「.COM」
console.log(x.split(".")[1]+ ".com");
另一個(亂)的方法(和將與.com.something
工作:
console.log(x.substring((x.indexOf("@ftp"))+5,x.indexOf(x.split("/")[3])-1));
而且也對這個我們dependend即將有「@ftp」和(在.com.something
在他們之後的至少3個或一個)的斜槓「/」,例如不會與工作:ftp://xxx:[email protected]
最後更新這將是我最好的
作品與.com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("@ftp.")[1]);
一如往常這取決於你想如何維護你的代碼,我只是想兌現肯定大約有到代碼的東西不止一種方法。我的回答肯定不是最好的,但基於它你可以改善你的問題。