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.
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.
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.
Z.