14

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>
user2435840
  • 143
  • 1
  • 1
  • 5
  • possible duplicate of [Why doesn't decodeURI("a+b") == "a b"?](http://stackoverflow.com/questions/4535288/why-doesnt-decodeuriab-a-b) – Dave Jun 09 '13 at 14:53
  • (specifically this answer seems to solve your problem: http://stackoverflow.com/a/4535319/1180785) – Dave Jun 09 '13 at 14:53

2 Answers2

31

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, ' '));
};
Wade
  • 582
  • 5
  • 10
  • 1
    javascript is full of surprises. One would bet decodeURIComponent (from its name) should also handle this case. – D_K Jun 03 '19 at 11:13
  • 5
    Since you are decoding it just after I would prefer replacing the old + symbol for its current one %20, so ```decodeURIComponent(str.replace(/\+/g, '%20'))``` – Watchmaker Nov 05 '19 at 17:17
  • 1
    Don't you mean `decodeURIComponent(filename).replace(/\+/g, ' ');`? – Emperor Eto Nov 11 '20 at 16:58
  • @PeterMoore if the `filename` contains `%2B`, `a %2B b` will turn into `a b` – syahid246 Jan 17 '23 at 04:18
7

You can use replace function for this:

decodeURI(query).replace( /\+/g, ' ' )
antyrat
  • 27,479
  • 9
  • 75
  • 76
  • 6
    This does not always work. If a user searches for "A+B C" an HTML form will encode it as "A%2B+C". The code above will decode this as "A%2B C". Instead you should first replace all +s with spaces then use decodeURIComponent (since we are not decoding a full URI but rather one parameter). – Wade Nov 27 '13 at 16:28