dimanche 23 juin 2019

Random string HTML escape issue, when using special chars

I was about to create a little javascript based tool, for quickly generating random strings, with, or w/o special chars and i found a nice snippet, which greatly inspired me: (https://stackoverflow.com/a/52464491/11689422):

function randStr(len) {
  let s = '';
  while (len--) s += String.fromCodePoint(Math.floor(Math.random() * (126 - 33) + 33));
  return s;
}

// usage
console.log(randStr(32));

This does the part of the job, when i want alphanumerical strings, with special chars too, but as soon, as i try to embed it into a HTML page, sometimes (actually, pretty frequently), the resulting string is randomly shorter, than the predefined length. It's ok though, when debugging in JS (the string's length is correct), but not on the html page, displayed with .innerHTML method). I also tried to use the following code, but the problem is the same:

function makeid(length) {
   var result           = '';
   var characters       = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&_-+=`|(){}[]:;\"'<>,.?/";
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

console.log(makeid(32));

Does anyone know a solution for this? Thanks a million in advance.




Aucun commentaire:

Enregistrer un commentaire