decodeURI将空间解码为+符号

use*_*840 7 javascript decode

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

代码是

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

Wad*_*ade 15

出于这个原因,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, ' '));
};
Run Code Online (Sandbox Code Playgroud)

  • 由于您在解码它之后我更愿意将旧的 + 符号替换为其当前的 %20,因此 ```decodeURIComponent(str.replace(/\+/g, '%20'))``` (3认同)

ant*_*rat 5

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

decodeURI(query).replace( /\+/g, ' ' )
Run Code Online (Sandbox Code Playgroud)

  • 这并不总是有效。如果用户搜索“A+B C”,HTML 表单会将其编码为“A%2B+C”。上面的代码将把它解码为“A%2B C”。相反,您应该首先用空格替换所有 +s 然后使用 decodeURIComponent (因为我们不是解码完整的 URI 而是一个参数)。 (5认同)