1

Is there a way to generate random String using JS. With '@', '.' sign in it I have been search for random string generation between a specific range this code works

function stringGen(len) {
    var text = " ";
    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ ) {
        text += charset.charAt(Math.floor(Math.random() * charset.length));
    }

    return text;
}

console.log(stringGen(3));

but there is no specific sign it it. I am creating a random email generator so please help me guys!

5 Answers 5

3

Just concatenate together until you got what you wanted

function stringGen(len) {
    var text = "";
    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ ) {
        text += charset.charAt(Math.floor(Math.random() * charset.length));
    }

    return text;
}

stringGen(10) + "@" + stringGen(5) + "." + stringGen(3)

I also changed the initialization of the variable text to an empty string.

If you want the TLD to be without digits:

function stringGen(len, num) {
    var text = "";
    var alpha = "abcdefghijklmnopqrstuvwxyz";
    var alnum = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ ) {
        if(!num)
          text += alnum.charAt(Math.floor(Math.random() * alnum.length));
        else
          text += alpha.charAt(Math.floor(Math.random() * alpha.length)); 
    }
    return text;
}

stringGen(10) + "@" + stringGen(5) + "." + stringGen(3,true)
Sign up to request clarification or add additional context in comments.

1 Comment

can you make the string gen after dot generate only string no number
1

The @ has to be after the first char and cannot be the last char. So choose a random position for it and use it if you reach this position:

function stringGen(len) {
    var text = "";
    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";
    var atPos = Math.floor(Math.random() * (len - 2)) + 1;

    for( var i=0; i < len; i++ ) {
      if(i==atPos) {
        text += '@'
      } else {
        text += charset.charAt(Math.floor(Math.random() * charset.length));
      }
    }

    return text;
}

A hostname with one char or digit is allowed by a RFC ( https://serverfault.com/questions/638260/is-it-valid-for-a-hostname-to-start-with-a-digit )

Comments

1

Why not just write another function that uses stringGen() multiple times?

function emailAddressGen () {
  var text = stringGen(Math.ceil(Math.random() * 10 + 2)); // length of 2 to 13
  text += '@';
  text += stringGen(Math.ceil(Math.random() * 10 + 2));
  text += '.';
  text += stringGen(Math.ceil(Math.random() + 2)); // length of 2 or 3
  return text;
}

You could also refactor that Math.ceil(Math.random() * n + m) nonsense out into a random number generator helper function that takes a range (m to n) or a single max integer.

function randomNum (arg) {
  var range = [0, 0];
  if (typeof arg === 'number') {
    range[1] = arg;
  else if (typeof arg === 'object') {
    range = arg;
  } else {
    return 'Wrong argument type: must be Array or Number';
  }

  return Math.floor(Math.random() * range[1] + range[0]);
}

Comments

1

Try this:

////
/// @author Nikhil Saini
/// @desc Random string generator function
/// @example var key = randomString("1-a-A-$-#-*"); gives key = 6-y-Z-<-r-@
/// @invocation randomString(pattern);
/// @param pattern: A string with random character identifiers
/// @default random identifiers:-
///     1: numerical digit,
///     a: lowercase alphabet
///     A: uppercase alphabet
///     #: alphanumeric character
///     $: special character
///     *: wildcard
/// @notes:
///     1. Characters that are not acting as identifiers will be preserved
///     2. Character sets can be customised/added by setting randomStringTable.<character-identifier> to desirable string of possible characters
////

///dictionary for possible characters
var randomStringTable = {
  "1": "1234567890",
  "a": "qwertyuiopasdfghjklzxcvbnm",
  "A": "QWERTYUIOPASDFGHJKLZXCVBNM",
  "$": "~!@#$%^&*()_+`{}:\"<>?|\\[];',./-=",
  "#": "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM",
  "*": "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM~!@#$%^&*()_+`{}:\"<>?|\\[];',./-="
};

/// function for random string generation
var randomString = pattern => {
  var randomString = "";
  for (var i = 0; i < pattern.length; i++) {
    var possibility = randomStringTable[pattern[i]];
    randomString += possibility ?
      possibility.charAt(Math.floor(Math.random() * possibility.length)) :
      pattern[i];
  }
  return randomString;
};

console.log(randomString("[email protected]"));

//the function can be cascaded also
console.log(randomString("a".repeat(randomString("1"))+"@"+"a".repeat(randomString("1"))+"."+"a".repeat(randomString("1"))));

Comments

0

Using the code you already have, you could place the @ at a random position in the string.

String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}

var email = '873gre8g9843f98';
email.replaceAt(Math.floor(Math.random()*email.length),'@');

1 Comment

But within a certain number of characters form the start or end. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.