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?

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,',');
Sign up to request clarification or add additional context in comments.

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,",");

Comments

0
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email=email.replace(/#/g,"@").replace(/!/g,".").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.