Open In App

How to create hash from string in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

To create a unique hash from a specific string, it can be implemented using its own string-to-hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256, and many more. 

These are the following methods to Create Hash from String:

Note: The hash value of an empty string is always zero. 

Method 1: Using JavaScript charCodeAt() method

The JavaScript str.charCodeAt() method returns a Unicode character set code unit of the character present at the index in the string specified as the argument. The index number ranges from 0 to n-1, where n is the string’s length.

Syntax:

str.charCodeAt(index)

Example: In this example, we will create a hash from a string in Javascript.

Javascript
function stringToHash(string) {

    let hash = 0;

    if (string.length == 0) return hash;

    for (i = 0; i < string.length; i++) {
        char = string.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash;
    }

    return hash;
}

// String printing in hash
let gfg = "GeeksforGeeks"
console.log(stringToHash(gfg));

Output
-1119635595

Method 2: Using crypto.createHash() method

The crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm. 

Syntax:

crypto.createHash( algorithm, options )

Example: In this example, we will create a hash from a string in Javascript.

JavaScript
// Importing 'crypto' module
const crypto = require('crypto'),

    // Returns the names of 
    // supported hash algorithms
    // such as SHA1,MD5
    hash = crypto.getHashes();

// Create hash of SHA1 type
x = "Geek"

// 'digest' is the output 
// of hash function containing
// only hexadecimal digits
hashPwd = crypto.createHash('sha1')
    .update(x).digest('hex');

console.log(hashPwd);

Output
321cca8846c784b6f2d6ba628f8502a5fb0683ae

Method 3: Using JavaScript String’s reduce() Method

The reduce() method in JavaScript applies a function to each element of the array (or in this case, each character of the string) to reduce the array to a single value. In this method, we can accumulate a hash value by iteratively processing each character’s Unicode code point and incorporating it into the hash.

Syntax:

string.split('').reduce((hash, char) => {
return char.charCodeAt(0) + (hash << 6) + (hash << 16) - hash;
}, 0);

Example:

JavaScript
function stringToHash(string) {
    return string.split('').reduce((hash, char) => {
        return char.charCodeAt(0) + (hash << 6) + (hash << 16) - hash;
    }, 0);
}

let gfg = "GeeksforGeeks";
console.log(stringToHash(gfg));

Output
-2465134923




Last Updated : 28 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads