How to create hash from string in JavaScript ?
Last Updated :
30 May, 2024
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.
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));
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);
Output321cca8846c784b6f2d6ba628f8502a5fb0683ae
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));
Using bitwise XOR operation
Using a bitwise XOR operation to generate a hash from a string. It iterates over each character, XORs its Unicode value with the current hash, updating it. This approach offers simplicity and efficiency in creating a unique hash.
Example: In this example we are using above-explained approach.
JavaScript
function stringToHash(string) {
let hash = 0;
if (string.length === 0) return hash;
for (const char of string) {
hash ^= char.charCodeAt(0); // Bitwise XOR operation
}
return hash;
}
// String printing in hash
const gfg = "GeeksforGeeks";
console.log(stringToHash(gfg));
Approach: Using Crypto library's createHash() method with SHA-256 algorithm
The Crypto library in Node.js provides a createHash() method that allows generating hash digests using various algorithms, including SHA-256. This method takes the algorithm name as an argument and returns a Hash object, which can then be used to update the hash with data and obtain the hash digest.
Example:
JavaScript
const crypto = require('crypto');
function createSHA256Hash(inputString) {
const hash = crypto.createHash('sha256');
hash.update(inputString);
return hash.digest('hex');
}
// Example usage
const inputString = "Hello, World!";
const hashValue = createSHA256Hash(inputString);
console.log(hashValue); // Output: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Similar Reads
How to Create JSON String in JavaScript?
JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
2 min read
How to create an element from a string in JavaScript ?
In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user. This can be achieved using many approaches as given below: Table of Content Using the createElement() methodUsing the
3 min read
How to Concatenate Strings in JavaScript?
Here are the various methods to concatenate strings in JavaScript1. Using Template Literals (Template Strings)Template literals (introduced in ES6) provide a simple way to concatenate strings. With template literals, you can embed expressions inside a string using ${} syntax. This method makes the c
3 min read
JavaScript - How to Get Character Array from String?
Here are the various methods to get character array from a string in JavaScript.1. Using String split() MethodThe split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. JavaScriptlet s = "Geeksf
2 min read
How to Add Backslash in JSON String JavaScript ?
In JavaScript, adding a backslash to a JSON string is important to properly escape special characters, ensuring the integrity and correctness of the JSON format for data processing and storage. Table of Content Using JSON.parse() and JSON.stringify()Using for LoopUsing Array.prototype.map() and Stri
2 min read
Convert Array to String in JavaScript
In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
7 min read
How to modify a string in JavaScript ?
JavaScript strings are used for storing and manipulating text. It can contain zero or more characters within quotes and its indexing starts with 0. Strings are defined as an array of characters. In Javascript, we can also convert strings to a Character array. Representing a String: 1. Using double
3 min read
How to Create a String with Variables in JavaScript?
To create a string with variables in JavaScript, you can use several methods, including string concatenation, template literals, and the String methods. Here are the common approaches:1. Template Literals (Recommended)Template literals are the modern and most preferred way to create strings with var
2 min read
How to Convert JSON to string in JavaScript ?
In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission.Several methods can be used
3 min read
How to Convert String to JSON in JavaScript?
In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
2 min read