0

I am trying to replace 3 chars with 3 other chars to build/mask an email address for a form.

This works only once or on the first instance of finding it:

email = "email1#domain!com|email2#domain!com|email3#domain!com";
email.replace("#","@").replace("!",".").replace("|",",");

The above code resulted in: [email protected],email2#domain!com|email3#domain!com

After some reading I read about using RegEx which is the portion of coding I can never wrap my head around:

email.replace("/#/g","@").replace("/!/g",".").replace("/|/g",",");

That didn't work either and left it the same as the original var.

What am I doing wrong?

asked Sep 25, 2012 at 22:26

3 Answers 3

4

Do not put quotes around the regex. Regexes are literals that use / as a boundary.

Additionally, you will need to escape the | because it has a special meaning.

Finally, .replace is not transformative. It returns the result.

email = email.replace(/#/g,'@').replace(/!/g,'.').replace(/\|/g,',');
answered Sep 25, 2012 at 22:29

1 Comment

Thanks - will accept this answer when I can in a few minutes!
1

Using regex literals, you omit the quotes (and you'll need to escape the pipe):

email.replace(/#/g,"@").replace(/!/g,".").replace(/\|/g,",");
answered Sep 25, 2012 at 22:28

Comments

0
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email=email.replace(/#/g,"@").replace(/!/g,".").replace(/\|/g,",");
answered Sep 25, 2012 at 22:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.