jadjoubran / codetogo.io

🚀 JavaScript code to go - Find updated snippets for common JavaScript use cases
https://codetogo.io
MIT License
233 stars 30 forks source link

Use case suggestion: How to get a random text/string #60

Closed jadjoubran closed 6 years ago

ghost commented 6 years ago

This can be the answer. Math.random().toString(36).substr(2);

jadjoubran commented 6 years ago

Thanks @mayankjain34 The problem with this one is that you can't specify how many random characters you want.. Do you know if there's a way to specify how many random characters you want? (of course while keeping it as simple as possible)

ghost commented 6 years ago

@jadjoubran if this is the case then this can be the answer.

function getRandomString(length) {
  let string = '';
  for(let i=0;i<length; i++) {
    string += getChar();
  }
  return string;
}

function getChar() {
/***
  ASCII code for
  numbers [48-57]
  alphabets [65-90, 97-122]
***/
  let max = 123;
  let min = 48;
  let num = Math.floor(Math.random() * (max - min)) + min
  if(num < 48 || (num > 57 && num < 65) || (num > 90 && num < 97) || (num > 122)) {
    return getChar();
  }
  return String.fromCharCode(num);
}

console.log(getRandomString(20))
jadjoubran commented 6 years ago

yeah, the problem however is that this is quite big to be included on codetogo I'll do some further research soon!

kakadiadarpan commented 6 years ago

How about this:

const length = 7;
const charIndex = 5; // value should be kept between 2 and 8
const randomString = [...Array(length)].map(
    () => Math.random().toString(36)[charIndex]
).join('') //generates "dblixbz"

The string generated by Math.random().toString(36) is something like this 0.p0hrpf1chg, the length of the string is around 10-12. That's the reason for keeping charIndex between 2 and 8.

This outputs a random text/sting of size length everytime:

screen shot 2018-03-11 at 19 18 01
jadjoubran commented 6 years ago

This is super cool @kakadiadarpan Will add the use case soon!

jadjoubran commented 6 years ago

I will also add that this should not be used for cryptography

jadjoubran commented 6 years ago

🎬 How to generate random string in JavaScript