Javascript replace all "%20" with a space

Viewed 155015

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"
7 Answers

using unescape(stringValue)

var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))

//Output
Passwords do not match!

use decodeURI(stringValue)

var str = "Passwords%20do%20not%20match%21";
 document.write(decodeURI(str))

Space = %20
? = %3F
! = %21
# = %23
...etc

This method uses the decodeURIComponent() (See edit below) method, which is the best one.

var str = "Passwords%20do%20not%20match%21";
alert(decodeURIComponent(str))

Here it how it works:

Space = %20
? = %3F
! = %21
# = %23
...etc

There's a good example of that at the Mozilla docs [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI]

Edit: decodeURIComponent works better, look at the example.

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)=>{
  //remove white space at the end 
  const arrString = string.split("")
  for(let i = arrString.length -1 ; i>=0 ; i--){
    let char = arrString[i];
    
    if(char.indexOf(" ") >=0){
     arrString.splice(i,1)
    }else{
      break;
    }
  }

  let start =0;
  let end = arrString.length -1;
  

  //add %20
  while(start < end){
    if(arrString[start].indexOf(' ') >=0){
      arrString[start] ="%20"
      
    }
    
    start++;
  }
  
  return arrString.join('');
}

console.log(stringQ1("Mr John Smith   "))

Related