DEV Community

Cover image for Generate Random String Using JavaScript
Sh Raj
Sh Raj

Posted on

2 2

Generate Random String Using JavaScript

Generate Random String

Video Documentation :- https://youtu.be/6QTVmiVwydc

Use this function

function getrandomString(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(getrandomString(5));//getrandomString function will return a string of length passed in it (5 here)

Enter fullscreen mode Exit fullscreen mode

Minified Version

function getrandomString(r){for(var t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=n.length,o=0;o<r;o++)t+=n.charAt(Math.floor(Math.random()*a));return t}
Enter fullscreen mode Exit fullscreen mode

Or Use This One Liner

if you will ever need a temporary unique id for something. this
one-liner will generate a random string for you

const randomString = Math.random().toString(36).slice(2);
console.log(randomString); //output- bg4v1vwslw4 (the string will be a random string )
Enter fullscreen mode Exit fullscreen mode

See Demo Website :- https://tutorials.sh20raj.repl.co/js/generate-random-string-using-javascript/

Fetch GitHub Markdown and Show on Blog Post or Website ft. showdownjs

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay