1

I created a function to delete the spaces out of a string and return the strings length with out spaces, however the function is deleting more then just the spaces. Also is there a better way of accomplishing this, assuming this function can be fixed.

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"
Brandon
  • 1,099
  • 1
  • 9
  • 14
  • The reason why some characters get lost will become evident if you try your function in this [Javascript tutor](http://pythontutor.com/javascript.html#mode=edit). You will see live how `splice` transforms the array inside the loop and thus changes the value of the indexes. – Ettore Rizza Feb 17 '17 at 22:46

7 Answers7

2

The reason why characters get lost, is because the list is modified inside the loop.

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

When you remove an character i, the next character will take its place.

You could maybe use the replace function instead like this:

string.replace(/ /gi, "").length
J. P. Petersen
  • 4,871
  • 4
  • 33
  • 33
2

When you remove a character from the string you'll have to go back one step (i--) st the loop won't skip a character (for(... ; i++)). Like this:

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

Snippet:

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

If you want to count characters that are not spaces:

Then just make a counter that will count the characters that are not spaces like this:

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));
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

Use regex.

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);
JM-AGMS
  • 1,670
  • 1
  • 15
  • 33
1

This is much simpler than you are doing. You can just use the .replace() string method which can take a string literal to replace or a regular expression.

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");
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

You don't need a regex: str.replace(" ","") is already doing that.

Siphalor
  • 712
  • 5
  • 16
1

Instead of this line here:

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

Try using this:

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

Just replaces the 1 with 0

Den Isahac
  • 1,335
  • 11
  • 26
1

You could use eiter a regular expression for filtering space

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

Or just test for space.

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

console.log(result);
console.log(result.length);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392