Is there a way to generate a random id (javascript preferred) via this format:?
7181cec4-cf43-5936-a75b-c1d5f8a7e00e
I need to create an id for each element in a JSON file in order to differentiate them when doing all kinds of sorting.
Is there a way to generate a random id (javascript preferred) via this format:?
7181cec4-cf43-5936-a75b-c1d5f8a7e00e
I need to create an id for each element in a JSON file in order to differentiate them when doing all kinds of sorting.
function randomAlphaNumeric () {
return Math.random().toString(36).charAt(2);
};
function createFromPattern (pattern) {
pattern = pattern.split('');
return pattern.map(x => x.replace('x', randomAlphaNumeric())).join('');
};
Will allow you to create your ID in whichever pattern you like, as long as it's in the format xxx-xxx
Example:
createFromPattern('xxx-xxx')
> "e6y-gzc"
createFromPattern('xxx-xxx-x-xxx-xxxx')
> "3w8-fch-t-fh3-h4uu"
createFromPattern('x-xxx-x')
> "c-yli-4"
Here's one way:
<script>
function RandomHexString(L) {
var hexstring='';
for(var i=0; i<L; i++) {
hexstring+=(Math.floor(Math.random() * 16)).toString(16);
}
return(hexstring);
}
console.log(RandomHexString(8) + '-' + RandomHexString(4) + '-' + RandomHexString(4) + '-' + RandomHexString(4) + '-' + RandomHexString(12));
</script>
This will produce outputs like:
a007bfd5-7883-6ac4-2a35-57efa2ab6fdc
7428b81f-4670-64ce-e02b-2ac97ae241bc