Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace all "%20" with a space

Tags:

javascript

Is there a way to replace every "%20" with a space using JavaScript. I know how to replace a single "%20" with a space but how do I replace all of them?

var str = "Passwords%20do%20not%20match";    var replaced = str.replace("%20", " "); // "Passwords do%20not%20match" 
like image 972
user3109009 Avatar asked Dec 26 '13 23:12

user3109009


People also ask

How do you replace all spaces?

Use the String. replaceAll() method to replace all spaces in a string, e.g. str. replaceAll(' ', '-'); . The replaceAll method will return a new string where all occurrences of a space have been replaced by the provided replacement.

Is there a Replace All in JavaScript?

Introduction to the JavaScript string replaceAll() methodTo replace all the occurrences of a substring with a new one, you can call the replace() method repeatedly or use a regular expression with a global flag ( g ). The pattern can be a string or a regular expression.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.


2 Answers

Check this out: How to replace all occurrences of a string in JavaScript?

Short answer:

str.replace(/%20/g, " "); 

EDIT: In this case you could also do the following:

decodeURI(str) 
like image 102
isset Avatar answered Sep 16 '22 17:09

isset


The percentage % sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20 is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".

Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?

var str = 'xPasswords%20do%20not%20match'; console.log( decodeURI(str) ); // "xPasswords do not match" 

Javascript has both decodeURI and decodeURIComponent which differ slightly in respect to their encodeURI and encodeURIComponent counterparts - you should familiarise yourself with the documentation.

like image 43
Emissary Avatar answered Sep 17 '22 17:09

Emissary