在JavaScript中逃避URL中的Ampersand

83 阅读1分钟

在这篇文章中,我们将看到如何在JavaScript中转义ampersand。

要在JavaScript中转义Ampersand,请使用encodeURIComponent() in JavaScript。

var ampersand = encodeURIComponent('&');
console.log(ampersand);

输出

%26

你可以看到,当我们调用encodeURIComponent ,它将& 编码为%26

你可以使用%来转义URL中不允许出现的字符。这里的&在十六进制中是26,这就是encodeURIComponent()& 转为%26 的原因。

让我们借助简单的例子来看看。

比方说,公司名称是A&B ,网址是。

http://example.com?company_name=A&B

如果不转义& ,那么你就不会得到预期的结果。

为了转义& ,你可以使用encodeURIComponent() ,如下所示

var link = 'http://example.com?company_name=' + encodeURIComponent('A&B');
console.log(link);

输出

http://example.com?company_name=A%26B

正如你所看到的,我们已经成功地转义了URL中的安培字。

在JavaScript中转义特殊字符的通用解决方案

我们的解决方案的好处是,它可以适用于任何特殊字符,你也可以使用同样的解决方案。

var link = 'http://example.com?company_name=' + encodeURIComponent('A&B>< ');
console.log(link);

输出

htp://example.com?company_name=A%26B%3E%3C%20

As you can see that we were able to successfully escape all special characters using encodeURIComponent().