Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to create hash from string in JavaScript ?

  • Difficulty Level : Hard
  • Last Updated : 14 Aug, 2019

In order to create a unique hash from a specific string, it can be implemented using their 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.

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Example 1:

<!DOCTYPE html>
        How to convert hash from
        string in JavaScript ?
        h1 {
            color: green;
        <h3>Creating hash from string in JavaScript?</h3>
        <p>The hash value of string "GeeksforGeeks" is .</p>
        <p id="geek"></p>
            // Convert to 32bit integer
            function stringToHash(string) {
                var 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
            var gfg = "GeeksforGeeks"
                        = stringToHash(gfg);


Example 2:

    // 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');



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!