window.history.pushState uri编码不一致

inconsistent window.history.pushState uri encoding

本文关键字:编码 不一致 uri pushState history window      更新时间:2023-09-26

获取url地址www.somesite.com/@user1

如果我点击一个包含链接的老式<a href...超链接,那么@在地址栏中被百分比编码为%40

如果我使用html5的window.history.pushstate("object or string", "Title", 'www.somesite.com/@user1'),则@而不是内插的,而是显示为"@"字符。

这种不一致性困扰着我。也许有办法让行为保持一致?

我已经考虑过将encodeURIComponent('www.somesite.com/@user1')用于pushstate url,但这也编码了"/",我希望<a href...超链接不编码"@"符号。

使用encodeURIComponent使javascript假设没有特殊的HTTP字符可以忽略。首先提取compnenet:

var url = "www.somesite.com/@user1";
var atPos = url.indexOf('@');
var urlComp= url.slice(atPos);  //@user1
url = url.slice(0, atPos);
url += encodeURIComponent(urlComp); //"www.somesite.com/%40user1"