Decoding URL parameters with JavaScript

user852367 picture user852367 · Aug 20, 2012 · Viewed 60.5k times · Source

This should be a simple task, but I can't seem to find a solution.

I have a basic string that is being passed through as a query string parameter like this one: This+is+a+message+with+spaces. I would like to decode that parameter using JavaScript to This is a message with spaces, but I cannot seem to get it to decode.

I've tried decodeURI('This+is+a+message+with+spaces') but the result still contains the + signs.

Answer

Supriti Panda picture Supriti Panda · May 16, 2013

Yes it is true that decodeURIComponent function doesn't convert + to space. So you have to replace the + using replace function.

Ideally the below solution works.

var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));