gpt4 book ai didi

Javascript:有选择地从 URL 中删除哈希(或哈希),以便 URL 保持有效或可用

转载 作者:行者123 更新时间:2023-11-30 21:13:42 27 4
gpt4 key购买 nike

假设我们有以下 url:

1. http://example.com#hash0
2. http://example.com#hash0#hash1
3. http://example.com#hash0/sample.net/
4. http://example.com#hash0/sample.net/#hash1
5. http://example.com#hash0/image.jpg
6. http://example.com#hash0/image.jpg#hash1
7. something.php#?type=abc&id=123
8. something.php#?type=abc&id=123#hash0
9. something.php/?type=abc&id=#123
....................................

还有更多此类排列,您明白了。我如何才能有选择地从此类 URL 中删除“不相关”的哈希值, 不会影响这些 URL 的功能(以便它们保持完整的链接或图像)?

例如,从这个列表中的编号 1 开始,我希望删除#hash0,从 2 中删除#hash0 和#hash1,从 3 中我想保留它,因为它后面是路径的延续 (是的,有可能,检查 here ),从 4 中只删除 #hash1,从 5 中保留它,但是从 6 中只删除 #hash1, ... ,我认为从 9 中保留它,因为它可能与查询(虽然不确定),等等。基本上,我只想删除后面没有任何可用内容(如路径、查询、图像文件等)的哈希值——“不相关”的哈希值,如#top、#bottom 等,指的是当前页面。

我正在做的事情还涉及从相对 URL 获取绝对 URL(在新 anchor 的 href 或新 URL 对象的 href 的帮助下),因此一个解决方案(如 here )可以“融入"与 location object's properties (如 .protocol、.host、.pathname、.search、.hash 等)更可取 - 因为它可能更“值得信赖”,因为它是内置的,但一个好的(和更短的)正则表达式也是可以接受的。总而言之,较短的解决方案更可取,因为我不希望我的项目在解析整个当前 URL 时为它遇到的每个链接或图像链接做额外的不必要的工作。

最佳答案

也许这就是您想要的,使用正则表达式。

var urls = [
'http://example.com#hash0', // remove
'http://example.com#hash0#hash1', // remove
'http://example.com#hash0/sample.net/', // keep
'http://example.com#hash0/sample.net/#hash1', // remove #hash1
'http://example.com#hash0/image.jpg', // keep
'http://example.com#hash0/image.jpg#hash1', // remove #hash1
'something.php#?type=abc&id=123', // keep
'something.php#?type=abc&id=123#hash0', // remove #hash0
'something.php/?type=abc&id=#123', // remove #123
],
result = urls.map(h => h.replace(/(?:#[^#\/\?\.]*)*#[^#\/\?\.]*$/gi, ''));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript:有选择地从 URL 中删除哈希(或哈希),以便 URL 保持有效或可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45886463/

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