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

后端 未结 9 878
我在风中等你
我在风中等你 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 13:09

    A bit cleaner and up-to-date approach:

    const email = "something@gmail.com"
    const domain = email.includes('@') && email.split("@").pop()
    

    Domain will be false if email doesn't contain @ symbol.

    0 讨论(0)
  • 2021-01-01 13:15

    Why not just do this.

    var email = "something@gmail.com", i = email.indexOf("@");
    if (i != -1) {
       email = email.substring(i);
    }
    

    Regex isn't really required, you could also go email = email.split("@")[1];

    0 讨论(0)
  • 2021-01-01 13:17

    Using a simple string split won't work on addresses like 'abc@abc'@example.com which is a valid address (technically). I believe splitting on @ and taking the last element should be fine, because no @ characters are allowed to appear in the domain.

    Or, since you requested, a regex: [^@]+$

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