JavaScript 获取页面的一部分 URL
JavaScript get portion of a page URL
有没有办法使用HTML css 和JavaScript 可以在前10 个字符后找到网页的URL。例如,如果 URL 是随机的。com/abc 程序只会获取 URl 的 /abc 部分并将其记录在控制台中。如何做到这一点?
您可以将 window.location.href
与 substring()
一起使用到 select 一定范围的字符或特定索引后的字符。
window.location.href.substring(10);
是的,您可以完成此操作,使用 window.location.href。
示例输出:
window.location.href: '
您现在可以分割这个字符串,得到想要的部分:
window.location.href.split('/')
输出:
0: "https:"
1: ""
2: "whosebug.com"
3: "questions"
4: "69409934"
5: "javascript-get-portion-of-a-page-url"
length: 6
现在将其登录到控制台:
console.log(window.location.href.split('/')[3])
你的结果:
'questions'
您需要从 window 位置对象中获取路径名。
window.location.pathname
要获取路径,请使用路径名。
console.log(window.location.pathname);
console.log((new URL('http://www.example.com/abc/123')).pathname);
没有理由拆分和使用索引。
有没有办法使用HTML css 和JavaScript 可以在前10 个字符后找到网页的URL。例如,如果 URL 是随机的。com/abc 程序只会获取 URl 的 /abc 部分并将其记录在控制台中。如何做到这一点?
您可以将 window.location.href
与 substring()
一起使用到 select 一定范围的字符或特定索引后的字符。
window.location.href.substring(10);
是的,您可以完成此操作,使用 window.location.href。
示例输出:
window.location.href: '
您现在可以分割这个字符串,得到想要的部分:
window.location.href.split('/')
输出:
0: "https:"
1: ""
2: "whosebug.com"
3: "questions"
4: "69409934"
5: "javascript-get-portion-of-a-page-url"
length: 6
现在将其登录到控制台:
console.log(window.location.href.split('/')[3])
你的结果:
'questions'
您需要从 window 位置对象中获取路径名。
window.location.pathname
要获取路径,请使用路径名。
console.log(window.location.pathname);
console.log((new URL('http://www.example.com/abc/123')).pathname);
没有理由拆分和使用索引。