從 JavaScript 中的 URL 字串中提取主機名?
若要從 URL 字串中提取主機名,請使用 split() 函式。以下是程式碼 −
示例
function gettingTheHostNameFromURL(websiteURL) {
var getTheHostName;
if (websiteURL.indexOf("//") > -1) {
getTheHostName = websiteURL.split('/')[2];
} else {
getTheHostName = websiteURL.split('/')[0];
}
getTheHostName = getTheHostName.split(':')[0];
getTheHostName = getTheHostName.split('?')[0];
return getTheHostName;
}
var websiteURL="https://tutorialspoint.tw/java/index.htm";var
websiteURL1="https://www.tutorix.com/about_us.htm";
var websiteURL2="https://tutorialspoint.tw/execute_python_online.php";
console.log(gettingTheHostNameFromURL(websiteURL))
console.log(gettingTheHostNameFromURL(websiteURL1))
console.log(gettingTheHostNameFromURL(websiteURL2))要執行上述程式,你需要使用以下命令 −
node fileName.js.
輸出
此處,我的檔名是 demo161.js。這將產生以下輸出 −
PS C:\Users\Amit\JavaScript-code> node demo161.js www.tutorialspoint.com www.tutorix.com www.tutorialspoint.com
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP