1

I am trying to replace all occurrences of a character in a string. This works when I use the RegExp() object to create the regular expression :

var str = "a-b-c-d";

var regex = new RegExp('\-','g');

str.replace(regex,'@');

So this works and I get "a@b@c@d".

What if I want to use an inline regular expression , say:

str.replace("/\-/g",'@')

it does not work. How do I do this without using RegExp();

1

1 Answer 1

4

Remove the quotes (Regex literal not string literal):

str.replace(/\-/g,'@')
Sign up to request clarification or add additional context in comments.

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.