How to use js to parse a url string to a url object All In One
How to use js to parse a url string to a url object All In One
如何利用js将url字符串解析为url对象
try
// const url = globalThis.window.location.href;
// const url = window.location.href;
const autoConvertPageToRepo = (page = ``) => {
if(!globalThis.window) {
throw new Error(`❌ 当前的 js 运行环境不支持 Web API!`)
}
let url = ``;
try {
if(!page) {
// in io page ✅
const host = window.location.host.split(`.`)[0];
const protocol = window.location.protocol;
const pathname = window.location.pathname;
url = `${protocol}//github.com/${host}${pathname}`;
} else {
// URL parser,ulr string => URL
}
console.log(`✅ repo url =`, url)
} catch (error) {
console.error(`❌ generate repo url error`, error)
}
return url;
}
// test cases
autoConvertPageToRepo();
// autoConvertPageToRepo(`https://txstc55.github.io/ugly-avatar/`);
// https://github.com/txstc55/ugly-avatar/
solution ✅
const autoConvertPageToRepo = (uri = ``) => {
if(!globalThis.window) {
throw new Error(`❌ 当前的 js 运行环境不支持 Web API!`)
}
let url = ``;
try {
if(!uri) {
// in io page ✅
const host = window.location.host.split(`.`)[0];
const protocol = window.location.protocol;
const pathname = window.location.pathname;
url = `${protocol}//github.com/${host}${pathname}`;
} else {
// URL parser,ulr string => URL 🚀
const location = new URL(uri);
const host = location.host.split(`.`)[0];
const protocol = location.protocol;
const pathname = location.pathname;
url = `${protocol}//github.com/${host}${pathname}`;
}
console.log(`✅ repo url =`, url)
} catch (error) {
console.error(`❌ generate repo url error`, error)
}
return url;
}
// test cases
autoConvertPageToRepo();
// autoConvertPageToRepo(`https://txstc55.github.io/ugly-avatar/`);
// ✅ repo url = https://github.com/txstc55/ugly-avatar/
demos
use js auto convert
GitHub Page URL
ToGitHub Repo URL
🚀
autoConvertPageToRepo();
// ✅ repo url = https://github.com/txstc55/ugly-avatar/
autoConvertPageToRepo(`https://txstc55.github.io/ugly-avatar/`);
// ✅ repo url = https://github.com/txstc55/ugly-avatar/
https://cdn.xgqfrms.xyz/github/github-page-to-github-repo.js
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
URL API
// window.location
const location = new URL(uri);
https://developer.mozilla.org/en-US/docs/Web/API/URL_API
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URL/parse_static
refs
https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
https://dmitripavlutin.com/parse-url-javascript/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18515232
未经授权禁止转载,违者必究!