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.
The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.
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.
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')); 
                        decodeURI function doesn't convert + to space, but there are some things worth to realize here: decodeURI is meant to be used for whole URI, i.e. it doesn't decode separators like ?, &, =, +, etc.decodeURIComponent should be used+ encoded as %2B, thus you should not replace + after the conversion since you might lost + signs that you actually want there, e.g. something?num=%2B632+905+123+4567 should become:something?num=+632 905 123 4567+632 905 123 4567 So the correct way to do this is:
var str = 'something?num=%2B632+905+123+4567'; decodeURIComponent( str.replace(/\+/g, '%20') ); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With