I am trying to create a random number as the keyName for a local storage for example in this code:
localStorage.setItem('_8bcsk999r778311o', input.value);
I want to create a random number in the place of "_8bcsk999r778311o" using javascript . Is it possible , and if possible , could you please send me the code? Thanks in advance!
Takes a number from 1 to 10 and save into number then with floor convert number to integer
//random integer from 0 to 10000:
let number = Math.floor(Math.random() * 10000);
localStorage.setItem(number, input.value);
In JavaScript, floor() is a function that is used to return the largest integer value that is less than or equal to a number. see more
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive): see more
const random_id = `_${Math.random().toString(30).substr(2,17) + Math.random().toString(30).substring(2,17)}`
console.log(random_id)
//localStorage.setItem(random_id, 'value goes here');
Very simple and fast solution
var key = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < Math.floor(10+10*Math.random()); i++) {
key += possible.charAt(Math.floor(Math.random() * possible.length));
}
localStorage.setItem(key, input.value);
I hope this will be helpful for you. Thanks.