从 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP