2

How can I remove all the left space without removing between & the right space of the string? And also when I changed the value of str the result will be the same. Only the left space will be removed.

function trimLeftSpace() {
    var str = "   Angry Bird   ";
    var splitTrim = str.split('');
    var trimStr = "";
    for (var index = 0; index < splitTrim.length; index++) { //trim left space
        if(splitTrim[index] != " ") {
            trimStr += str[index];
        }
    }
    return trimStr;
 }
0

7 Answers 7

2

Your current solution creates a new string which contains all the non-space characters of the original string, you need to stop looking for spaces as soon as you find a non-space character. Here is an example:

function trimLeftSpace(str) {
    var doneTrimming = false
    var ret = ""
    for (var index = 0; index < str.length; index++) {
        if(str[index] !== ' '){
            doneTrimming = true
        }
        if(doneTrimming){
            ret += str[index]
        }
    }
    return ret;
}

var result = trimLeftSpace("   Angry Bird   ");
console.log("|"+result+"|");

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

3 Comments

how about I want to remove right space? This code helped me a lot!
@LizQuenUpdate You can use the same code, you just need to reverse the original string before you run it then, when it is done, reverse the result.
@LizQuenUpdate Actually, it will be much easier to loop the original string from end to start and add the characters to the start of the result. For example: for (var index = str.length - 1; index >= 0; index--) and ret = str[index] + ret
2

To trim the beginning of the string, use a simple regex to replace the whitespaces in the beginning of the string:

var str = "   Angry Bird   ";

function trimLeftSpace(str) {
  return str.replace(/^\s+/, '');
}

console.log('"' + trimLeftSpace(str) + '"');

Or just use .trimStart():

var str = "   Angry Bird   ";

function trimLeftSpace(str) {
  return str.trimStart();
}

console.log('"' + trimLeftSpace(str) + '"');

Comments

1

You could try a regex replacement:

var str = "   Angry Bird   ";
str = str.replace( new RegExp("^\\s+", "gm"),"");
console.log('"' + str + '"');

1 Comment

@ibrahimmahrir Yes, I hear this often about RegExp. Sadly, many highly viewed SO questions still promote it.
0

This will remove all whitespace on the left of the string:

function trimLeftSpace(str) {
  var result = "";
  for(var i = 0; i < str.length; i++) {
    if(str[i] != " ") {
      return str.slice(i);
      break;
    } else {
      result += str[i];
    }
  }
  return result;
}

console.log(trimLeftSpace("   Angry Birds   Angry Birds"));

Comments

0

Try this

function trimLeftSpace(str) {
    return str.replace(/\s+$/, '')
}

var result = trimLeftSpace("   Angry Bird   ");
console.log("|"+result+"|");

Comments

0

If you want to use a function instead of regex solutions from the other answers, then make a function that looks for the first non-space character, then use slice to cut only the part of the string that's after it:

function customTrim(str) {
  for(var i = 0; i < str.length; i++) {
    if(str.charAt(i) !== " ") {
      return str.slice(i);
    }
  }
}

var res = customTrim("    Snake Shot    ");
console.log('"' + res + '"');

Notes:

  • This only looks for spaces ' '. If you want to look for tabs '\t', newlines '\n', ... then just add them to the if test (sperate them with &&).
  • If an empty or space-only strings are passed, then undefined is returned, if you don't want that then just return an empty string at the bottom of the function to make it the default return value.

Comments

0

You could try a regex replacement:

   let variable = "hello world";
   let removeRegex = /^\s+|\s+$/g;
   let removeSpace = variable.replace(removeRegex,"");
   console.log(removeSpace);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.