Megahnanda Bintang
Megahnanda Bintang

Reputation: 13

Javascript Code to Append a String Each Character

i have this string:

"Abcd"

i want to append a string ("Z") each character above:

result:

"AZbZcZdZ"

please help me, i have searched this in stackoverflow, but no result..

please forgive me about my bad English. :)

Thanks.

Upvotes: 1

Views: 161

Answers (3)

Josh
Josh

Reputation: 8191

While replace is one way, you can also use split and join and concatenate the last Z:

"Abcd".split('').join('Z') + 'Z'; // Outputs: AZbZcZdZ

As @VizioN mentioned and to my surprise for this short string, this is also not faster than regex.

UPDATE: This is faster than using a regular expression, even with longer strings. Unsure what the results used to show, but the previous link I provided that supposedly shows that split/join is slower, is actually faster by a considerable percentage.

Upvotes: 0

Julien Grenier
Julien Grenier

Reputation: 3394

Use this regex: "Abcd".replace(/(.)/g, "$1Z");

explanation :

(.): Capture each character in a group.

g: Tell the regex to search the entire string.

$1: is each captured characters.

Upvotes: 0

VisioN
VisioN

Reputation: 145398

The easiest way is to use regular expression in .replace():

"Abcd".replace(/./g, "$&Z");

Here /./g will match all symbols in the given string and $& will insert them in the output.

Upvotes: 4

Related Questions