11

我创建了一个谷歌自定义搜索。逻辑是当用户搜索时,页面将显示结果,页面的标题将更改为使用 javascript 的搜索词。我使用 decodeURI 来解码 unicode 字符。但是空间被解码为+。例如,如果我搜索赚钱,它将被解码为赚钱+赚钱,并显示为标题。有人请帮助解决这个问题。我想显示空格而不是符号 +。

代码是

 if (query != null){document.title = decodeURI(query)+" | Tamil Search";}</script>
4

2 回答 2

25

正是出于这个原因, Google Closure Library提供了自己的 urlDecode 函数。您可以使用该库或以下是他们如何解决它的开源解决方案。

/**
 * URL-decodes the string. We need to specially handle '+'s because
 * the javascript library doesn't convert them to spaces.
 * @param {string} str The string to url decode.
 * @return {string} The decoded {@code str}.
 */
goog.string.urlDecode = function(str) {
  return decodeURIComponent(str.replace(/\+/g, ' '));
};
于 2013-11-27T16:10:22.970 回答
7

您可以为此使用替换功能:

decodeURI(query).replace( /\+/g, ' ' )
于 2013-06-09T13:36:04.380 回答