Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decodeURI decodes space as + symbol

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>
like image 287
user2435840 Avatar asked Jun 09 '13 13:06

user2435840


People also ask

What is difference between decodeURI and decodeURIComponent?

decodeURI(): It takes encodeURI(url) string as parameter and returns the decoded string. decodeURIComponent(): It takes encodeURIComponent(url) string as parameter and returns the decoded string.

What is decodeURI?

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or by a similar routine.

Why do we use decodeURIComponent?

The decodeURIComponent() function is used to decode URI components. In other words, it is useful when you want a quick function for a URL decode. The abbreviation URI refers to a URI. js library used to manage URLs.

What is encodeURI and decodeURI in JavaScript?

encodeURI() and decodeURI() functions in JavaScript. The encodeURI() function encodes the complete URI including special characters except except (, / ? : @ & = + $ #) characters. The decodeURI() function decodes the URI generated by the encodeURI() function.


2 Answers

You can use replace function for this:

decodeURI(query).replace( /\+/g, ' ' )
like image 103
antyrat Avatar answered Sep 21 '22 15:09

antyrat


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, ' '));
};
like image 45
Wade Avatar answered Sep 20 '22 15:09

Wade