Skip to content
Advertisement

Joining numbers together with a string

I know that for an array join() can be used to produce what I am trying to accomplish here, but I am working with a string. What method would work with a string?

I want my output to look like “3 then 4 then 5 then 6 then 7”, etc.

I’ve come close to getting what I am looking for but my current code adds an extra “then” at the end, which is not what I want:

let appendString = '';
let then = ' then ';

function countUp(start) {
  for(var i = 0; i < 10; i++){     
    appendString += (start++) + then; 
  }   
  console.log(appendString); 
}

I do not want solutions, I just would appreciate being pointed in the right direction.

Advertisement

Answer

what about this?

let appendString = '';
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){     
  appendString += (start++)
  if(i<9){
    appendString+=then
  }
  
}   
console.log(appendString); 
}

or

let appendArray = [];
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){     
  appendArray.push(start++);
}   

console.log(appendArray.join(then)); 
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement