javascript decodeURI 将空格解码为 + 符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17010119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:45:38  来源:igfitidea点击:

decodeURI decodes space as + symbol

javascriptdecode

提问by user2435840

I have created a Google Custom Search. The logic is when a user search, the page will display result and the title of the page will be changed to the search term using javascript. I use decodeURI to decode the unicode characters. But the space is decode as +. For example if I search money making it will be decoded as money+making and it is displayed as title. Someone please help to solve this. I want to display space instead of the symbol +.

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

The code is

代码是

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

回答by Wade

The Google Closure Libraryprovides its own urlDecode function for just this reason. You can either use the library or below is the open source solutionfor how they solve it.

正是出于这个原因,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, ' '));
};

回答by antyrat

You can use replace function for this:

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

decodeURI(query).replace( /\+/g, ' ' )