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

November 20, 2018 No comments QA random id JavaScript

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.

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