Decode a PHP encoded string url in Javascript

Sometimes you may face a problem when you have to decode a string with Javascript which was originally url encoded with PHP. This can be an API response or cookie set by PHP setcookie function.

A simple way to do this is through decodeURIComponent function in Javascript. But it leaves the "+" signs in the string. For that we can use replace function to replace all the "+" signs with space. Remember, simply using replace function sign will only replace the first occurrence in the string. To replace all the occurrences, use the regex version with g flag.

Here is the code for your reference-

var decodedString = decodeURIComponent( encodedString ).replace( /+/g, ' ' );

Here encodedString is the url encoded string received from PHP.

Its that simple!

If you have any other method, do share in comments.

Happy coding!

Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *