在 JavaScript 中从 URL 字符串中提取主机名?

javascriptweb developmentobject oriented programming更新于 2025/11/17 18:20:17

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

相关文章


有用资源