decodeURI decodes space as + symbol

user2435840 picture user2435840 · Jun 9, 2013 · Viewed 12.3k times · Source

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 +.

The code is

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

Answer

Wade picture Wade · Nov 27, 2013

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

/**
 * 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, ' '));
};