0

This small piece of PHP code generates tokens with very good entropy. I would like to know if there is a function in JavaScript that can accomplish the same. Examples are welcome.

Here's the PHP

function getToken($length) {

    $token = "";
    $codeAlphabet  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet .= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet .= "0123456789";

    $max = strlen($codeAlphabet);

    for ($i=0; $i < $length; $i++) {
        $token .= $codeAlphabet[random_int(0, $max-1)];
    }

    return $token;
}

echo getToken(24);
0

1 Answer 1

1

Doing almost the same thing..

function getToken(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(getToken(10));

Example with Jquery

$( document ).ready(function() {

	// set the length of the string
	var stringLength = 10;

	// list containing characters for the random string
	var stringArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
  'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','!','?'];

	$("#generateToken").click(function (){

		var rndString = "";
	
		// build a string with random characters
		for (var i = 1; i < stringLength; i++) { 
			var rndNum = Math.ceil(Math.random() * stringArray.length) - 1;
			rndString = rndString + stringArray[rndNum];
		};
		
		$("#showToken").html('<p><strong>' + rndString + '<strong></p>');

	});

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click the button below to generate a new, randomized token.</p>
<button id="generateToken">Generate New Token</button>
<p id="showToken"></p>

Sign up to request clarification or add additional context in comments.

4 Comments

Nice. Since you've mentioned almost, is there a difference worth noting?
Should be exactly the samething sorry for speling wrong
At the very least give a reference or close the question as a duplicate when you copy code from a highly upvoted answer: https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
@icecub I got this from a video tuturoial on youtube to use for reseting password about 3 years ago, guy name was JOHN something, didnt see that answer and didnt copy from there. its a token generating script almost all of them are same if you search on internet. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.