preg: how to write a preg pattern to get domain name from an email?

后端 未结 9 877
我在风中等你
我在风中等你 2021-01-01 12:43

From an email address like something@gmail.com I want to fetch domain name gmail.com. i want to use that pattern on textbox value in Javascript.

相关标签:
9条回答
  • 2021-01-01 12:50

    You can do this

    var extract_company_name = function(email){
      var temp = email.replace(/.*@/, '').split('.');
        return temp[temp.length - 2];
    }
    extract_company_name(email)
    

    this will fetch the domain from any email.

    code in jsbin

    0 讨论(0)
  • 2021-01-01 12:51
    var email = 'test@gmail.com';
    var domain = email.replace(/.*@/, "").split('.')[0];
    console.log(domain); // gmail
    
    0 讨论(0)
  • 2021-01-01 12:52

    You can replace everything up to and including the @ symbol to get the domain. In Javascript:

    var email = 'test@gmail.com';
    var domain = email.replace(/.*@/, "");
    alert(domain);
    
    0 讨论(0)
  • 2021-01-01 12:54

    I have just experience a need to implement this and came up with the solution that combines most of already mentioned techniques:

    var email = "test@test@gmail.com";
    var email_string_array = email.split("@");
    var domain_string_location = email_string_array.length -1;
    var final_domain = email_string_array[domain_string_location];
    

    So if email has multiple @ characters then you just need to split email string by "@" and calculate how many elements are there in new created array then subtract 1 from it and you can take right element from array with that number.

    Here is the jsfiddle: http://jsfiddle.net/47yqn/

    It has show 100% success for me!

    0 讨论(0)
  • 2021-01-01 12:56

    You can do this to get domain name from url,email,website,with http started,only domain name

    var str=inputAddress;
          var patt1 = "(http://|https://|ftp://|www.|[a-z0-9._%+-]+@)([^/\r\n]+)(/[^\r\n]*)?";
    var result = str.match(patt1);
    var domain=result===null?str:result[2];
    return domain.toString().startsWith("www.")?domain.toString().slice(4):domain;
    
    0 讨论(0)
  • 2021-01-01 13:09

    I would try

    \b.*@([A-Za-z0-9.-]+\.[A-Za-z]{2,4})\b
    

    Or maybe tune it a little replacing \bs by ^ and $. With this you can match any domain with A-Z, a-z and 0-9 characters.

    0 讨论(0)
提交回复
热议问题