使用循环的空白替换javascript的更有效的解决方案

时间:2019-03-21 21:48:39

标签: javascript loops

this can be found in other forums and posts like what people have said thank you.

我正在尝试使用用%20替换“”的循环来创建函数,但是如果字符串“”之前和之后的空格没有用%20替换,那么我在这里使用循环来解决这是必需的,我只是想知道如果我可以使它更精确和简洁,将不胜感激。

console.log(urlEncode("Hello World"));
console.log(urlEncode(" Hello World "));
console.log(urlEncode("This is my Hello World Program"));

Hello%20World
Hello%20World <--- if their is space before or after it does not count
This%20is%20my%20Hello%20World%20Program

4 个答案:

答案 0 :(得分:3)

怎么样:

const urlEncode = function(text) {
    return text.trim().replace(/\b \b/g, '%20')
}

这使用内置的replace方法并匹配由两个非空格包围的空格。

如果您真的想使用循环:

const urlEncode = function(text) {
    const n = text.length;
    const start = text[0] === ' ' ? 1 : 0;
    const end = text[n - 1] === ' ' ? n - 1 : n;
    let result = "";

    for (let i = start; i < end; i++) {
         result += text[i] == ' ' ? '%20' : text[i];
    }

    return result;
}

答案 1 :(得分:1)

请参阅Thomas的评论。使用javascript本机的encodeURIComponent可能是最简单和最安全的。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

答案 2 :(得分:1)

我确定在您应该再做一些研究朋友之前,已经回答了这个问题,但这是一个选择。

const urlEncode = (str) => {
  return str.trim().replace(/\s/g, '%20');
}

编辑:啊,哥卡错过了循环部分

const urlEncode = (str) => {
  str = str.trim();
  let encodedStr = '';
  let index = 0;
  for (let i = 0; i < str.length; i++) {
    if(str[i] === ' ') {
      encodedStr += str.slice(index, i)+'%20';
      index = i+1;
    }
  }
  return encodedStr + str.split(' ').pop();
};

我仍然必须使用split。我会继续思考。

Edit3:知道了!

const urlEncode = (str) => {
  str = str.trim();
  let encodedStr = '';
  let index = 0;
  for (let i = 0; i < str.length; i++) {
    if(str[i] === ' ') {
      encodedStr += str.slice(index, i)+'%20';
      index = i+1;
    }
  }
  return encodedStr + str.slice(index, str.length);
};

如果您有任何疑问,请随时提问!

答案 3 :(得分:0)

function urlEncode(txt){
  let text = txt.split("");
  let acc = "";
  for(let i = 0; i < text.length; i++){
    let curr = text[i];
    let ret = curr;
    let inx = i;
    if(curr === " " && (inx === 0 || (inx === txt.length - 1))){
      ret = " ";
    } else if(curr === " "){
      ret = "%20";
    }
    acc += ret;
  }
  return acc;
}