JavaScript: create a unique ID from a string

In this article we'll see how to create a unique ID from a given string. Our implementation involves the use of arrays with random keys and an utility function that eliminates duplicates from an array. Let's see the details.

First we create our utility function:

function eliminateDuplicates(arr) {
    var i, len = arr.length,
        out = [],
        obj = {};

    for (i = 0; i < len; i++) {
        obj[arr[i]] = 0;
    }
    for (i in obj) {
        out.push(i);
    }
    return out;
}

Then we can create our main function:

var uniqid = function(str) {
    var len = str.length;
    var chars = [];
    for (var i = 0; i < len; i++) {

        chars[i] = str[Math.floor((Math.random() * len))];

    }

    var filtered = eliminateDuplicates(chars);

    return filtered.join('');


}

Always remember to use the random() method together with the floor() method in order to get consistent results. Here's an example:

alert(uniqid('lorem1234'));​

You can see the demo below.

Demo

Live demo

Back to top