0

How to generate unique UID from some specific string in javascript.

eq.

var string = "this is some string that will generate unique UID"  
var unique_UID = somefunction(string)

and everytime when I will call somefunction(string) this will generate same unique_UID if the string is same.

Thank you in advance!

  • 4
    `function somefunction (str) { return str; }` looks unique to me. – epascarello Sep 21 '13 at 17:57
  • while it does not generate a uuid from a string [this question's answers](http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript) do generate unique ids, you could probably modify them to use a string as the seed – Patrick Evans Sep 21 '13 at 17:58
  • Do you expect to get different, unique results when you give the same input string? Or are you just asking how to scramble the string into something that looks random (i.e. a hash code)? – Barmar Sep 21 '13 at 18:04
  • @PatrickEvans that function return random uid because use Math.random and everytime is used will generate another UID – user1863881 Sep 21 '13 at 18:16
  • @Barmar I expect to get same UID as long the string is same – user1863881 Sep 21 '13 at 18:18
  • Then use a hashing function like `MD5`, `SHA1`, or one of the algorithms in http://www.php.net/manual/en/function.hash-algos.php – Barmar Sep 21 '13 at 18:24
  • @Barmar I need that function in JavaScript – user1863881 Sep 21 '13 at 18:27
  • 1
    possible duplicate of [Generate a Hash from string in Javascript/jQuery](http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery) – Barmar Sep 21 '13 at 18:41
  • I totally agree with @epascarello It is exactly what you need. What is wrong with this solution? It satisfies all the conditions you've mentioned. Also `function somefunction(str){return 1;}` satisfies your conditions. You have to be more precise in what you want. – freakish Sep 21 '13 at 19:13

2 Answers2

0

You may want something like this

function randomString(str) {
    var uid = ''; str = str.replace(/\s/g, '');
    for (var i = str.length; i > 0; --i) {
        uid += str[Math.round(Math.random() * (str.length - 1))];
    }
    return uid;
}
var uid = randomString('this is some string that will generate unique UID');
console.log(uid); // tnwtrieitiUnilwuteerhnrnthtqwritmutteqeua

DEMO.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

Looks like you need a hash function. Try to use crypto-js:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
<script>
    var hash = CryptoJS.MD5("Message");
</script>
Andrey M.
  • 3,688
  • 3
  • 33
  • 36