0

I need a Math. and print random chars of random lengths.

example:

124543achg
hhed23
gdgdf14
61dsfffffq
gs18

Tried

const randomText = Math.random().toString(36).substr(2, 5); + Math.random().toString(36).substr(2, 5)

but it giving me all the time same lengths! I want to randomize the lengths.

minimum 1, max 15

2 Answers2

2

Answer from Generate random string/characters in JavaScript

const makeid = (length) => {
  const result = [];
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for ( let i = 0; i < length; i += 1 ) {
    result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));
  }
  return result.join('');
}

console.log(makeid(5));

You can randomize the length outside the function:

// Generate integer between 1 and 15
const randomLength = Math.floor(Math.random() * (15 - 1) + 1);
console.log(makeid(randomLength));

Or inside:

const makeid = (min, max) => {
  // Generate integer between min and max
  const length = Math.floor(Math.random() * (max - min) + min);
  const result = [];
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for ( let i = 0; i < length; i += 1 ) {
    result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));
  }
  return result.join('');
}

console.log(makeid(1, 15));
1

I would use Math.random for both string length and string caracters.

const lettersNumbers = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

const randomLen = Math.ceil(Math.random() * 15);

const randomStr = (length, chars) => {
  let result = '';
  for (var i = length; i > 0; --i) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
}
const r = randomStr(randomLen, lettersNumbers);
console.log(r);
Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29