generate hash from string

How to Generate Hash from String in JavaScript

Often websites and apps are required to create hash from strings for generating keys or encrypting data before transmitting or storing it. This process is commonly known as hashing whereby a hash consisting of alphabets, numbers & symbols is generated from a given string. In this article, we will learn how to generate hash from string in JavaScript.


How to Generate Hash from String in JavaScript

Here is a simple code snippet to generate hash from string in JavaScript.

String.prototype.hashCode = function() {
  var hash = 0,
    i, chr;
  if (this.length === 0) return hash;
  for (i = 0; i < this.length; i++) {
    chr = this.charCodeAt(i);
    hash = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
}

const str = 'good morning';
console.log(str, str.hashCode())

The above function uses the same logic as used in other programming languages like Java, to generate hash of a given string. It initiates hash to empty string, and basically loops through a given string one character at a time. In each iteration, it multiplies hash by 31 and then adds the character’s ascii value to it to update the hash. It does so by left shifting the hash string by 5 places ( multiply by 32) and then subtract the hash value from it. Lastly, we convert the updated hash into 32bit integer. We have used bitwise – shift operator << instead of multiplication operator * to multiply hash by 31. This is because shift operator is faster than multiplication operator and works well even for large strings.

We have defined a prototype instead of a standalone function so that it can be directly called on any string.

Most modern browsers support reduce() function which speeds up function execution in many cases. If your web browser supports reduce() function, then you can modify the above code as shown below.

hashCode = function(s){
  return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
}

The above code uses the same logic of left shifting existing hash string by 5 places (multiply 32) and then subtracting hash from the result.

In this article, we have learnt how to generate hash from string. You can add this code to your modules, where you need to generate hash from strings.

Also read:

How to List Properties of JS Object
How to Detect If Device is iOS
How to Count Character Occurrence in JS String
How to Add Auto Increment Field to MySQL Table
JS File Upload Size Validation

Leave a Reply

Your email address will not be published. Required fields are marked *