0
var my_string = "some text goes here!!!";

Why is it that my_string.replace('!', '*', my_string); only gives

some text goes here!!*

instead of some text goes here*** ?

Any idea?

1
  • 2
    Add global fla g. Commented Mar 29, 2013 at 15:26

3 Answers 3

5

By default replace() only replaces the first occurrence. To replace all occurrences, pass in the global flag, as in:

var my_string = str.replace(/!/g,"*");
Sign up to request clarification or add additional context in comments.

Comments

1

you can perform a global replacement by using g..

The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

var replaced_string=  my_string.replace(/!/g, '*');

Comments

1

You need to use the global flag g. This should suit your needs:

.replace(/!/g, '*');

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.