如何编码&在URL中不是查询参数的一部分?

时间:2016-05-04 16:29:41

标签: javascript xslt

我从XML获取数据并构建一个传递给Pinterest的URL。

Pinterest网址结构

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-butter-jelly-sandwich.html&media=http%3A%2F%2Fwww.test.com/images/pbjs.jpg&description=Peanut%20Butter%20%26%20Jelly%20Sandwich

XSLT 1.0或JS中有哪些选项可以帮助我解决这个问题?

编辑1:增加了预期的输出。

编辑2:事实证明,在我们的网站中有另一段代码执行重定向,并且需要在编码之后使用特殊字符。它造成了不兼容。

1 个答案:

答案 0 :(得分:1)

在将其添加到网址之前,您需要转义[description]

"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);