1

I am trying to use this block of code to replace ALL "123"'s in a long string with a different number.

   var new_id = new Date().getTime();
    $('#food').after(
      "<div id='123' name='123'> etc etc".replace('123', new_id)
    );

But it's only replacing the first 123 with the new_id. Is there a way to replace all of them?

2 Answers 2

6

You need to make it a regex instead of a plain vanilla string and add the /g flag.

"<div id='123' name='123'> etc etc".replace(/123/g, new_id)
Sign up to request clarification or add additional context in comments.

Comments

5

replace(/123/g, new_id)

This is regex literal syntax with a global (g) flag.

Comments

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.