如何从 JavaScript 中的 url 获取路径名值? [英] How can I get pathname values from url in JavaScript?
本文介绍了如何从 JavaScript 中的 url 获取路径名值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
http://example.com/iu4pa9rm8vfh.html?param_1
我想要这个:
iu4pa9rm8vfh
var url ="http://example.com/iu4pa9rm8vfh.html?param_1";
document.getElementById("demo").innerHTML =
"The pathname of this page is :" + url.pathname;
提前感谢您的指导!
更新结果有什么问题
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const url = new URL("http://example.com/iu4pa9rm8vfh.html?param_1")
const pathname = url.pathname.match(/([0-9a-z]+)/)
console.log(pathname[0])
document.getElementById("demo").innerHTML = "The pathname of this page is :" + pathname;
</script>
</body>
</html>
推荐答案
你可以这样做:
const url = new URL('http://example.com/iu4pa9rm8vfh.html?param_1')
let path = url.pathname.split('.')[0].replace('/','')
document.getElementById("demo").innerHTML = "The pathname of this page is :" + path;
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const url = new URL('http://example.com/iu4pa9rm8vfh.html?param_1')
let path = url.pathname.split('.')[0].replace('/','')
document.getElementById("demo").innerHTML = "The pathname of this page is :" + path;
</script>
</body>
</html>
这篇关于如何从 JavaScript 中的 url 获取路径名值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文