javascripthash

Generate a Hash from string in Javascript


I need to convert strings to some form of hash. Is this possible in JavaScript?

I'm not utilizing a server-side language so I can't do it that way.


Solution

  • const generateHash = (string) => {
      let hash = 0;
      for (const char of string) {
        hash = (hash << 5) - hash + char.charCodeAt(0);
        hash |= 0; // Constrain to 32bit integer
      }
      return hash;
    };
    
    console.log(generateHash('revenue'))