如何在搜索前清理“+”登录网址?

时间:2011-02-05 05:58:23

标签: javascript search

// Description: I try to search Wolframalpha.com with JS search
// but I get an odd action with "+" sign, apparently because "+" is
// not just to sum things. Here an example:

var query=1+2;

// WA interpretes "+" to "%2B" after the execution
// but when I try to replace "+" with "%2B"
// WA replaces "%2B" with %225B"
// So replacing this way may end up into some odd loop
//
// How should I replace "+"/sanitize correctly?
// Or am I do it the wrong way? How to search WA in JS?

query=query.replace("+","%2B");


var url = 'http://www.wolframalpha.com/input/?i=';
var searchUrl = url + escape(query);
window.open(searchUrl, form.target || "_blank");

2 个答案:

答案 0 :(得分:3)

escape不适用于网址编码。它做了类似但不同的事情。您想要encodeURIComponentlink)。您还需要围绕query var值(下面第一行)的引号:

var query="1+2";

var url = 'http://www.wolframalpha.com/input/?i=';
var searchUrl = url + encodeURIComponent(query);
window.open(searchUrl, form.target || "_blank");

Live example

encodeURIComponent会正确编码+

答案 1 :(得分:0)

我认为您的问题是var query=1+2;它没有将query作为字符串处理,因此replace不是可在线query=query.replace("+","%2B");上调用的函数

需要var query='1+2';