为什么这个字符串解析功能不起作用?

时间:2017-02-17 22:01:19

标签: javascript

我创建了一个函数来删除字符串中的空格并使用out空格返回字符串长度,但是该函数正在删除更多的空格。假设可以修复此功能,还有更好的方法来实现这一点。

let string="This string is going to lose characters";

function charLength(str){
    let strArray=str.split("");
    let output="";

    for(let i=0; i < strArray.length; i++){
        if(strArray[i]===" "){
            strArray.splice(strArray[i],1);
        }
        else{
            output+=strArray[i];
        }
    }
    return output.length // + " " output, if I were to add this you would see its deleting characters
}

charLength(string);//returns "27 Thistringsoingooseharacters", not "33 Thisstringisgoingtolosecharacters"

7 个答案:

答案 0 :(得分:2)

字符丢失的原因是因为列表在循环内被修改。

for(let i=0; i < strArray.length; i++){
    if(strArray[i]===" "){
        strArray.splice(strArray[i],1);  // Items are removed here
    ...

删除字符i后,下一个字符将取代它。

您可以使用replace功能,而不是这样:

string.replace(/ /gi, "").length

答案 1 :(得分:2)

从字符串中删除字符时,您必须返回一步(i--),否则循环不会跳过字符(for(... ; i++))。像这样:

if (strArray[i] === " ") {
  strArray.splice(strArray[i], 1);
  i--; // ge back one step if we remove one character.
}

<强>段:

let string = "This string is not going to lose characters";

function charLength(str) {
  let strArray = str.split("");
  let output = "";

  for (let i = 0; i < strArray.length; i++) {
    if (strArray[i] === " ") {
      strArray.splice(strArray[i], 1);
      i--;
    } else {
      output += strArray[i];
    }
  }
  return output;
}

console.log(charLength(string));

如果您想要计算不是空格的字符:

然后只需创建一个计数器来计算不是这样的空格的字符:

let string = "This string is not going to lose characters";

function charLength(str) {
  let counter = 0;                        // the counter
  for (let i = 0; i < str.length; i++) {  // for each character in the string
    if(str.charAt(i) !== ' ')             // if the character is not a space
      counter++;                          // increment the counter
  }
  return counter;
}

console.log(charLength(string));

答案 2 :(得分:1)

使用正则表达式。

var str = 'This string is going to lose characters';

// The substituted value will be contained in the result variable
const result = str.replace(/\s/g, '');

console.log('Substitution result: ', result.length);

答案 3 :(得分:1)

这比你做的要简单得多。您可以使用 .replace() 字符串方法,该方法可以将字符串文字替换为正则表达式。

&#13;
&#13;
function charLength(str){

    // Create a new string that is the same as the passed in one, but with the spaces stripped out
    // The syntax / / denotes a regular expresion (regEx) object 
    // The s+ denotes to look for one or more spaces in a row
    // The g denotes a global search and replace througout the string 
    var newStr = str.replace(/\s+/g, "");

    console.log("\"" + str + "\" has: " + str.length + " characters."); 
    console.log("\"" + newStr + "\" has: " + newStr.length + " characters."); 
}

charLength("This string is going to lose characters");
&#13;
&#13;
&#13;

答案 4 :(得分:1)

你不需要正则表达式:str.replace(&#34;&#34;,&#34;&#34;)已经在做了。

答案 5 :(得分:1)

而不是这一行:

strArray.splice(strArray[i],1);

尝试使用:

strArray.splice(strArray[i],0);

只需将1替换为0

即可

答案 6 :(得分:1)

您可以使用正则表达式来过滤空间

&#13;
&#13;
var string = "This string is going to lose characters",
    result = [...string].filter(RegExp.prototype.test.bind(RegExp('[^ ]'))).join('');

console.log(result);
console.log(result.length);
&#13;
&#13;
&#13;

或者只是测试空间。

&#13;
&#13;
var string = "This string is going to lose characters",
    result = [...string].filter(a => a !== ' ').join('');

console.log(result);
console.log(result.length);
&#13;
&#13;
&#13;