Skip to content

Javascript generate unique number based on string

Lets say I have a string var input = "Foo" and I need a 100% unique number from that string, I tried something like

for (var i = 0, len = input.length; i < len; i++) {
      output += input[i].charCodeAt(0)

But this generates duplicates like W8M and YSM and both return the id of 149.

Is there an algorithm for something like this?



You want a hash function. Hash functions are generally not unique (as in, there are collisions), but the keyspace is so vast that you might live entire lifetimes without finding one in your app.

Look for SHA1 and SHA256 implementations for JavaScript for a start, if you’re using node, look at the crypto module.

User contributions licensed under: CC BY-SA
1 People found this is helpful