如何编码&在不是't是查询参数的一部分

How to encode & in URL that isn't part of the query parameter?

本文关键字:查询 参数 一部分 何编码 编码 amp      更新时间:2023-09-26

我正在从XML中获取数据,并构建一个url以传递给Pinterest。

Pinterest的URL结构是

https://www.pinterest.com/pin/create/button/?url=[URL]&media=[media URL]&description=[description]

由于我无法控制的原因,XML中的[description]字段有一个与字符。示例:"花生酱果冻三明治"

如果我试图将整个Pinterest URL放入encodeURIComponent()中;变为%26,但它不是查询参数&。

期望输出应该是:https://www.pinterest.com/pin/create/button/?url=http%3A%2F%2Fwww.test.com%2Frecipe%2Fpeanut-奶油冻三明治。html&media=http%3A%2F%2Fwww.test.com/images/pbjs.jpg&description=花生%20黄油%20%26%20果冻%20三明治

XSLT1.0或JS中有哪些选项可以帮助我处理这个问题?

第1版:添加了预期输出。

第二版:原来在我们的网站上还有另一段代码在执行重定向,它需要对其后面的特殊字符进行编码。它造成了不兼容。

在将[description]添加到url之前,您需要对其进行转义。

"https://www.pinterest.com/pin/create/button/?url=[URL]&media=[media URL]&description=" + escape("Peanut Butter & Jelly Sandwich")

或者你可以做

var data = {
    url: 'http://google.com',
    media: 'http://media/url',
    description: 'Peanut Butter & Jelly Sandwich'
};
var pinterest_url = 'https://www.pinterest.com/pin/create/button/?url=[url]&media=[media]&description=[description]';
for (var key in data) {
    pinterest_url = pinterest_url.replace("[" + key + "]", escape(data[key]));
}
alert(pinterest_url);