Javascript replace all “%20” with a space

假如想象 提交于 2019-12-17 10:35:40

问题


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"

回答1:


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)



回答2:


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.




回答3:


Use the global flag in regexp:

var replaced = str.replace(/%20/g, " ");
                                ^



回答4:


using unescape(stringValue)

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

decodeURI(stringValue) only works with space(" ") other char not work properly

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



回答5:


If you want to use jQuery you can use .replaceAll()




回答6:


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


来源:https://stackoverflow.com/questions/20792572/javascript-replace-all-20-with-a-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!