假设我们有以下网址:
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 个我希望从 2 个中删除 #hash0 #hash0 和 #hash1,从 3 个中删除我想保留它,因为它后面是路径的延续(是的,这是可能的,检查这里(,从 4 删除仅 #hash1,从 5 保留它,但从 6 删除只是 #hash1, ...,从 9 开始,我认为保留它,因为它可能与查询相关(虽然不确定(,依此类推。基本上,我只想删除后面没有任何可用内容的哈希(如路径、查询、图像文件等(——"不相关"的哈希,如 #top、#bottom 等,指的是当前页面。
我正在研究一些还涉及从相对 URL 获取绝对 URL 的事情(借助新锚点的 href 或新 URL 对象的 href(,因此可以与位置对象的属性(如 .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; }