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"
1
  • The reason why some characters get lost will become evident if you try your function in this Javascript tutor. You will see live how splice transforms the array inside the loop and thus changes the value of the indexes. Commented Feb 17, 2017 at 22:46

7 Answers 7

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

1

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

Comments

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.