1

I am currently working on a project where I have to generate some email addresses on the fly in javascript, based on some generic strings with various characters.

Say i have a couple of group names:

var groupname1: "This is my first group";
var groupname2: "This.is.yet@another@!#¤%&/()     group";

I need to figure out which characters to strip from the names, so i can make them email-valid

function removeWeirdCharsAndReturnEmailAddress(name){
  var emailValidString = [DO REGEX/OTHER MAGIC HERE];
  return emailValidString + '@domain.org';
}
swearhouse
  • 47
  • 8

2 Answers2

1

Try this. It will consider what's on the left of the '@' per your question and strip out non email body characters. The regex I've used isn't perfect. You can tailor it to your requirement:

function removeWeirdCharsAndReturnEmailAddress(name){
    var indexOfAt = name.indexOf("@");
    var s = '';
    if (indexOfAt > -1)
      s = str.substring(0, indexOfAt);
    else
      s='do something in case no @ in string';

    var acceptedString = '';
    for (var i = 0, len = s.length; i < len; i++) {
        if (isValidEmailCharacter(s[i])) acceptedString += s[i];
    }

      return acceptedString + '@domain.org';
  }

  function isValidEmailCharacter(s){
     var re = /[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]/;
     return re.test(s);
  }
Ash
  • 5,786
  • 5
  • 22
  • 42
  • It'd be good to have some reference about where the regexp in `isValidEmailCharacter()` comes from. But I'm pretty sure that an address like `-|.@domain.org` is not valid. – Álvaro González Jul 07 '16 at 08:48
  • I came up with the reg exp...it's something that simply accepts single characters with a to z A to Z numbers and some allowed special characters. As mentioned, it needs some work. Domain.Org is what the OP used in his question and is obviously just for demonstration's sake – Ash Jul 07 '16 at 09:28
0

You can create valid emails with generator library.

Check Chance.js.

Code is very simple:

chance.email({domain: 'example.com'})
=> 'giigjom@example.com'
Ygalbel
  • 5,214
  • 1
  • 24
  • 32
  • That library doesn't seem to do what the OP is asking for (strip or transliterate a given string and use it for the local part). – Álvaro González Jul 07 '16 at 08:47
  • You right, but he said he works on a project to generate emails. This library can help him in this job. – Ygalbel Jul 07 '16 at 08:51