0

I have to parse (in JS) an e-mail address that originally, instead of a @ has a dot. Obviously I want to show the @ instead of the dot.

var mail = "name.domain.xx"

We have two cases:

  1. name contains some dots itself and they are backslashed:

    name\.surname.domain.xx
    
  2. name contains only regular characters (non dots)

In this topic I found a way to implement the negative lookbehind and this is what I did:

mail = mail.replace(/(\\)?\./, function ($0, $1) { return $1?$0:"@"; });

but it's not working because in case (1) it finds the \., it does not touch it, and of course it stops.

On the other end, if I use the option g, it substitute also the third dot obtaining name.surname@domain@xx

Now, is there a way to say: I want to look in the whole string but I want to stop in the first match? I hope I explained myself.

Cheers

Community
  • 1
  • 1
valenz
  • 311
  • 1
  • 2
  • 13

1 Answers1

0

I misunderstood when first answering your question. So I have changed my answer.

If you don't put the /g flag, it will just replace the first match, meaning you can look for the first punctuation without a \ in front of it. Second you can replace all the \. belonging to the user part of the email with a regular punctuation.

http://jsfiddle.net/GLVNY/2/

var emailSingle = 'myname.domain.com',
    emailDouble = 'my\\.name\\.another\\.name.domain.com',
    regAt = /([^\\])\./,
    repAt = '$1@',
    regPunct = /\\./g,
    repPunct = '.';

emailSingle = emailSingle.replace(regAt, repAt).replace(regPunct, repPunct);
emailDouble = emailDouble.replace(regAt, repAt).replace(regPunct, repPunct);

alert('emailSingle: ' + emailSingle + '\nemailDouble: ' + emailDouble);
thebreiflabb
  • 1,504
  • 10
  • 19
  • It is possible you just do not replace all \. and only first . – kuncajs May 10 '13 at 10:45
  • @kuncajs That is possible to do yes. – thebreiflabb May 10 '13 at 10:47
  • @thebreiflabb: thanks! It works great but I have to take care of the subdomains as well. At this point I will probably leave the address as it is...explaining the notation. – valenz May 10 '13 at 10:58
  • But I cannot believe that there is no way to start from left, skip all the \. and match the first . It's so frustrating.. – valenz May 10 '13 at 11:05
  • @user2283224 Oh does the string actually contain the `\\` character before the punction between the names, and not in the domain part? Then there should be a solution! – thebreiflabb May 10 '13 at 11:08
  • @thebreiflabb: yes, that's what I wrote in the question. And yes! That's working! Thank you very much!! I am trying to understand how, but it works! – valenz May 10 '13 at 12:17