Add characters to a string in Javascript

JavascriptStringFor Loop

Javascript Problem Overview


I need to add in a For Loop characters to an empty string. I know that you can use the function concat in Javascript to do concats with strings

var first_name = "peter"; 
var last_name = "jones"; 
var name=first_name.concat(last_name) 

But it doesn't work with my example. Any idea of how to do it in another way?

My code :

var text ="";
for (var member in list) {
  text.concat(list[member]);
}

Javascript Solutions


Solution 1 - Javascript

let text = "";
for(let member in list) {
  text += list[member];
}

Solution 2 - Javascript

You can also keep adding strings to an existing string like so:

var myString = "Hello ";
myString += "World";
myString += "!";

the result would be -> Hello World!

Solution 3 - Javascript

simply used the + operator. Javascript concats strings with +

Solution 4 - Javascript

To use String.concat, you need to replace your existing text, since the function does not act by reference.

let text = "";
for (const member in list) {
  text = text.concat(list[member]);
}

Of course, the join() or += suggestions offered by others will work fine as well.

Solution 5 - Javascript

It sounds like you want to use join, e.g.:

var text = list.join();

Solution 6 - Javascript

Simple use text = text + string2

Solution 7 - Javascript

You can also use string interpolation

let text = "";
for(let member in list) {
  text = `${text}${list[member]}`;
}

Solution 8 - Javascript

Try this. It adds the same char multiple times to a string

const addCharsToString = (string, char, howManyTimes) => {
  string + new Array(howManyTimes).fill(char).join('')
} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrunoView Question on Stackoverflow
Solution 1 - JavascriptBlazesView Answer on Stackoverflow
Solution 2 - JavascriptMatt SichView Answer on Stackoverflow
Solution 3 - JavascriptneebzView Answer on Stackoverflow
Solution 4 - JavascriptBrett ZamirView Answer on Stackoverflow
Solution 5 - JavascriptWalter RumsbyView Answer on Stackoverflow
Solution 6 - JavascriptsraView Answer on Stackoverflow
Solution 7 - JavascriptshmuelsView Answer on Stackoverflow
Solution 8 - JavascriptNagibabaView Answer on Stackoverflow