Solid javascript encode uri

Solid javascript encode uri

本文关键字:uri encode javascript Solid      更新时间:2023-09-26

我读过这篇文章和更多文章:

什么时候应该使用 escape 而不是 encodeURI/encodeURIComponent?

我仍然没有找到可靠的编码/解码 uri 解决方案。

假设我有这些变量

var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';

未编码的网址将是:

var url 'http://example.com/?first=' + first + '&second=' + second + '&third=' + third + '&fourth=' + fourth;

稍后它应该在 ajax 请求中,例如:

xhr = new XMLHttpRequest();
xhr.open('POST', url );

我试过这个:

var url 'http://example.com/?first=' + encodeURIComponent(first);

但它不适用于#.那么什么是适用于所有字符的可靠编码解决方案?

我不使用 jQuery,只使用 javascript。

在编码 uri 参数时使用encodeURIComponent。当您使用该函数对主题标签进行编码时,它将产生字符串"%23"。

所以在你的例子中:

var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
var url = 'http://example.com/?first=' + encodeURIComponent(first) + '&second=' + encodeURIComponent(second) + '&third=' + encodeURIComponent(third) + '&fourth=' + encodeURIComponent(fourth);

将导致包含以下字符串的 url 变量:

http://example.com/?first=Hello%26and&second=Let's%20have%20cite&third=And%20%22hash%2C.%23%24&fourth=%C3%A5%C3%A4%C3%B6%20other%20strange%20chars

有关encodeURIComponent功能的更多信息,请参见此处。

(引自W3学校)此函数对特殊字符进行编码。在 此外,它还编码以下字符:、/?: @ & = + $ #

您可以尝试使用escape()函数。这救了我很多次。

escape('#')确实会产生%23