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
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,',');
1 Comment
Using regex literals, you omit the quotes (and you'll need to escape the pipe):
email.replace(/#/g,"@").replace(/!/g,".").replace(/\|/g,",");
Comments
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email=email.replace(/#/g,"@").replace(/!/g,".").replace(/\|/g,",");