从 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.com/java/index.htm";var
websiteURL1="https://www.tutorix.com/about_us.htm";
var websiteURL2="https://tutorialspoint.com/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

更新于: 12-Sep-2020

625 次浏览

开启您的 职业生涯

完成这门课程,获得认证

上手
广告
© . All rights reserved.