How to generate a random string in JavaScript in a single line of code

July 27, 2019 No comments QA random id JavaScript

1. Introduction

Sometimes there is a need to have a random string in javascript to uniquely identify panels or other elements in DOM. If you are looking for fast and one line solution, you can use this snippet and adapt to your own requirements.

2. Random identifier

The following inline function will generate a random characters:

var randomId = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
for (var i = 0; i < 10; i ++) console.log(Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10));

Output:

gmsf6ewxcfpzze6j
025yl9pw7uvv6ooo
6b6ivast0ymr2zmi
5xp6txjjzpyfcbau
8bjkdbpasouu1pnj
k453wg7720lcoatf
zm91lq0sx1et79ci
icuqi4l1ltq9bne0
jkfikuoyg8ngpnmr
a0znn508ymamf4ja
{{ message }}

{{ 'Comments are closed.' | trans }}