Reputation: 45
I need to have a JavaScript alert without the space between last word and exclamation mark.
The final alert should look like:
I like my own garden verymuchmuch verymuchmuch!
Here is the code with which I have space before.
var inittext, closetext, msg = "";
var i, j, k;
var myarray = new Array(3);
myarray[0] = "my";
myarray[1] = "own";
myarray[2] = "garden";
inittext = "I like ";
closetext = "!";
for (k=0; k < 3; k++) {
inittext = inittext + myarray[k] + " ";
}
for (j=0; j < 2; j++){
inittext = inittext + "very";
for (i=0; i < 2; i++){
inittext = inittext + "much";
}
inittext = inittext +" ";
}
msg = inittext + closetext;
alert(msg);
Upvotes: 1
Views: 54
Reputation: 2738
You could check to not add the white space in this way:
var inittext, closetext, msg = "";
var i, j, k;
var myarray = new Array(3);
myarray[0] = "my";
myarray[1] = "own";
myarray[2] = "garden";
inittext = "I like ";
closetext = "!";
for (k=0; k < 3; k++) {
inittext = inittext + myarray[k] + " ";
}
for (j=0; j < 2; j++){
inittext = inittext + "very";
for (i=0; i < 2; i++){
inittext = inittext + "much";
}
inittext = inittext + (j<1 ? " " : "");
}
msg = inittext + closetext;
alert(msg);
or you can just trim the inittex variable msg = inittext.trim() + closetext;
Upvotes: 0
Reputation: 290
It looks like the closetext variable contains the ! and the inittext is where the extra space is added in because of inittext + " " even when there is nothing after the last time that is called, so try
msg = inittext.trim() + closetext;
Upvotes: 1