Javascript replace all “ ” with a space

前端 未结 6 693
走了就别回头了
走了就别回头了 2020-12-02 20:00

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?

         


        
6条回答
  •  猫巷女王i
    2020-12-02 20:39

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

提交回复
热议问题