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"
This question is related to
javascript
Use the global
flag in regexp:
var replaced = str.replace(/%20/g, " ");
^
using unescape(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))
_x000D_
//Output
Passwords do not match!
use decodeURI(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(decodeURI(str))
_x000D_
Space = %20
? = %3F
! = %21
# = %23
...etc
If you want to use jQuery you can use .replaceAll()
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.
If you need to remove white spaces at the end then here is a solution: https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/
const stringQ1 = (string)=>{_x000D_
//remove white space at the end _x000D_
const arrString = string.split("")_x000D_
for(let i = arrString.length -1 ; i>=0 ; i--){_x000D_
let char = arrString[i];_x000D_
_x000D_
if(char.indexOf(" ") >=0){_x000D_
arrString.splice(i,1)_x000D_
}else{_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
let start =0;_x000D_
let end = arrString.length -1;_x000D_
_x000D_
_x000D_
//add %20_x000D_
while(start < end){_x000D_
if(arrString[start].indexOf(' ') >=0){_x000D_
arrString[start] ="%20"_x000D_
_x000D_
}_x000D_
_x000D_
start++;_x000D_
}_x000D_
_x000D_
return arrString.join('');_x000D_
}_x000D_
_x000D_
console.log(stringQ1("Mr John Smith "))
_x000D_
Source: Stackoverflow.com