olo
olo

Reputation: 5271

2 strings replace javascript

I am a beginner, how do I combine them:

var mystring = "[email protected]";
document.write(mystring.replace(/@/, "&&"));

prints my.email&&computer.com

var mystring = "[email protected]";
document.write(mystring.replace(/\./, "##"));

prints my##[email protected]

I have two questions: How do I make this regex (mystring.replace(/./, "##") to after @ change the dot to ## and how can I combine those two lines into one, and final read is:my.email&&computer##com

Upvotes: 1

Views: 215

Answers (5)

leoinfo
leoinfo

Reputation: 8195

This should work:

var mystring = "[email protected]";
document.write(mystring.replace(/(.*?)(@)(.*?)(\.)(.*)/, "$1&&$3##$5"));

Result:

my.email&&computer##com

See it here working: http://jsfiddle.net/gnB85/

Upvotes: 1

Rain Diao
Rain Diao

Reputation: 926

input : [email protected]

result : my.first.last.email&&example##computer##com

Solution 1:

var mystring = "[email protected]";
//replace '.' after '@' with '##', then replace '@' with '&&'.
var result = mystring.replace(/(?!.*@)\./g, "##").replace(/@/, "&&");
document.write(result);

Solution 2 (configurable):

var mystring = "[email protected]";

var replacements = {
                    '@' : '&&',
                    '.' : '##'
                   };

var str =  "[email protected]";

//match latter part of the string
var result = str.replace(/@\w+(\.\w+)+/g, function(at_and_after) {
    //replace all '.' and '@' in that part.
    return at_and_after.replace(/@|\./g, function(m) { return replacements[m]});
});
document.write(result);  //console.log(result) or alert(result) is a better way for demo

Upvotes: 4

ATOzTOA
ATOzTOA

Reputation: 35950

Try this...

var mystring = "[email protected]";
document.write(mystring.replace(/(.*@.*)\./, "$1##").replace(/@/, "&&"));

Upvotes: 2

rbernabe
rbernabe

Reputation: 1072

Try this:

var mystring = "[email protected]"
document.write(mystring.replace(/\.(?!\w+@)/, '##').replace(/@/, '&&'));

Upvotes: 0

Michael Day
Michael Day

Reputation: 1015

You could use split to split the string at /@/ and apply the second regexp to the second part of the string, then join the results back together with &&.

Upvotes: 1

Related Questions