1

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

5 Comments

Nope, it won't append the last Z.
That is a little trivial. Append Z.
You need to do: "Abcd".split('').join('Z') + "Z";
What you say is wrong. Regex will work faster for longer strings and will grasp less memory than you need to work with array.
@VisioN After looking more into it, you are right! That is my bad. In the end, it's just a slower alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.