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