Skip to content

JavaScript random string | alpha-numeric Example

  • by

Generating Pure JavaScript random string is needed some code of logic, you can do it by using for loop, math floor, and random method.

What’s the best way to generate random string/characters in JavaScript?

Answer: Example of 5 character strings composed of characters picked randomly from the set [a-zA-Z0-9] in JS. Random alpha-numeric (uppercase, lowercase, and numbers) code:-

<!DOCTYPE html>
<html>
	<body>

	<script>
	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;
		}

	alert(makeid(5));
	
	</script>

</body>
</html>

Output:

generate random string characters in JavaScript

How to generate Javascript generate unique string?

Answer:

You should use .length property of your string of possible characters(charset).

Also, use Math.floor a method in order to get integer positions of your chars array.

You can get a random item from charset string using its array index:

You can do same way to generating 5 char random string in JavaScript.

<!DOCTYPE html>
<html>
	<body>

	<script>
	var anysize = 3;//the size of string 
	var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
	result="";
	for( var i=0; i < anysize; i++ )
        	result += charset[Math.floor(Math.random() * charset.length)];

	alert(result);
	
	</script>

</body>
</html>

Output:

generate Javascript generate unique string

Do comment if you have any doubts and suggestion on this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading