Bruno
Bruno

Reputation: 9027

Add characters to a string in Javascript

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]);
}

Upvotes: 148

Views: 604365

Answers (9)

Arthur Zennig
Arthur Zennig

Reputation: 2184

your array of strings (list) could work with map and join; (Also possible to additionally change strings if you want)

var text = list.map(i => `${i}`).join(' ') 

would return First Name

but if you want to add more things around the name, above template also helps:

var text = list.map(i => `'${i}'`).join(' ') 

would return 'First' 'Name'

and in case you would want to have a sequence of names, separeted by comma

var text = list.map(i => `'${i}'`).join(',') 

would return 'First','Name','Second','Third',...

Upvotes: 1

Nagibaba
Nagibaba

Reputation: 5358

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

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

Upvotes: 2

shmuels
shmuels

Reputation: 1393

You can also use string interpolation

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

Upvotes: 1

Blazes
Blazes

Reputation: 4779

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

Upvotes: 197

Brett Zamir
Brett Zamir

Reputation: 14345

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.

Upvotes: 6

Matt Sich
Matt Sich

Reputation: 4105

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

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

the result would be -> Hello World!

Upvotes: 74

Walter Rumsby
Walter Rumsby

Reputation: 7535

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

var text = list.join();

Upvotes: 6

sra
sra

Reputation: 23973

Simple use text = text + string2

Upvotes: 4

neeebzz
neeebzz

Reputation: 11538

simply used the + operator. Javascript concats strings with +

Upvotes: 12

Related Questions