yerassyl
yerassyl

Reputation: 3048

JavaScript string concatenation adds extra space at the end

var code ='';
alert(branch+"t"); // resutl: 123t
for(var i=0;i<endVar;i++){
  code = code+branch;
}
alert(code);// result: 123 123 123 etc..
I have branch string var and code var. If I do alert branch+"t" I get 123t, so I suppose I don't have any spaces at the end in my branch var. But after doing for loop and alerting code var I get 123 123 123, so I get spaces added after each concatenation of branch to code var. What can be the problem?

Upvotes: 2

Views: 3036

Answers (3)

Patrice Gagnon
Patrice Gagnon

Reputation: 1454

I belive you didn't copy your entire code. The "branch" var cannot 123, if it was the case, you would not see a space:

https://jsfiddle.net/59hqc2ck/

var code ='';
var branch = 123;
var endVar = 10;
alert(branch+"t"); // resutl: 123t
for(var i=0;i<endVar;i++){
  code = code+branch;
}

alert(code);

Upvotes: 0

Filipe Merker
Filipe Merker

Reputation: 2446

Your main problem may be a space in the left side, not in the right. So,try trimming your data.

var code ='';
alert(branch+"t"); // resutl: 123t
for(var i=0;i<endVar;i++){
  //the .trim() here will handle the spaces
  code = code+branch.trim();
}
alert(code);

Why?

Well, trimming is a well known practice in back-end development because you never can predict exactly what is going into your variables. So, trimming will remove all spaces from both sides of your string. I think this is your way to go, validating your data is always safe.

Upvotes: 5

ergonaut
ergonaut

Reputation: 7057

It seems like branch has an extra space

branch = ' 123'.

Just make sure you remove it and it won't append extra spaces each time.

Upvotes: 1

Related Questions