gpt4 book ai didi

javascript - 剥离变量 : javascript 中的文本

转载 作者:行者123 更新时间:2023-11-30 09:08:08 40 4
gpt4 key购买 nike

考虑像这样的变量

var url='http://www.example.com/index.php?id=ss';

var url='http://www.example.com/dir1/dir2/index.php';

在这些变量中,我只想获取域部分,即 http://www.example.com,去除其他文本。这在普通的 javascript 或 jquery 中可能吗?

请帮忙

最佳答案

无需争论 URL 字符串。浏览器有自己的 URL 解析器,您可以使用 HTMLAnchorElement 的类似 location 的属性访问它:

var a= document.createElement('a');
a.href= 'http://www.example.com/index.php?id=ss';

alert(a.protocol); // http
alert(a.hostname); // www.example.com
alert(a.pathname); // /index.php
alert(a.search); // ?id=ss
// also port, hash

关于javascript - 剥离变量 : javascript 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3102830/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com