The shorter the hash, the higher the chances of collision.
However, in the Java world, there is a string hashCode
helper that returns a "not so unique" integer out of a string, and it's the smallest way to map a string as ID, but it doesn't guarantee uniqueness and it suffers collisions.
Accordingly, I strongly discourage you to use this in the wild, but for answer sake, here how you can play around with such hash:
function hashCode(s) {
for (var h = 0, i = 0; i < s.length; h &= h)
h = 31 * h + s.charCodeAt(i++);
return h;
}
On the other hand, sha256 is a one way hashing that "doesn't suffer collisions" (it does, but much less than MD5, SHA1, or the hashCode
up there), so while the result is a longer unique id, it's kinda granted to always work as expected, and it's explained in MDN.
P.S. NodeJS 15+ has a crypto.webcrypto
namespace that is identical to the Web one, so you can use the same code in browsers and server.