How to Create Hash From String in JavaScript?
Last Updated :
28 Jun, 2025
To create a hash from a string in JavaScript, you can use hashing algorithms like MD5, SHA-1, or SHA-256. Here are the different methods to create HASH from string in JavaScript.
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)
JavaScript
function toHash(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(toHash(gfg));
2. Using crypto.createHash() method
The crypto.createHash() method in Node.js is used to create a hash object that can generate a hash of a given data using a specified algorithm, such as SHA-256, SHA-512, or MD5.
Syntax
const crypto = require('crypto');
const hash = crypto.createHash(algorithm);
- algorithm: A string representing the hashing algorithm to be used (e.g., 'sha256', 'sha512', 'md5').
- hash: The hash object that allows the hashing process to be updated with data and then generates the final hash.
JavaScript
const crypto = require('crypto'),
hash = crypto.getHashes();
x = "Geek"
hashPwd = crypto.createHash('sha1')
.update(x).digest('hex');
console.log(hashPwd);
Output321cca8846c784b6f2d6ba628f8502a5fb0683ae
In this example
- Import crypto module: Allows access to cryptographic functions.
- Define input string: Sets the string to be hashed.
- Create SHA-1 hash: Creates a SHA-1 hash and converts the input string into its hex representation.
- Log the hash: Prints the resulting hash of "Geek" to the console.
3. Using JavaScript String's reduce() Method
The reduce() method in JavaScript is typically used with arrays to reduce them to a single value. It can also be used with strings to create custom operations, like generating a simple hash from a string.
JavaScript
function toHash(string) {
return string.split('').reduce((hash, char) => {
return char.charCodeAt(0) + (hash << 6) + (hash << 16) - hash;
}, 0);
}
let gfg = "GeeksforGeeks";
console.log(toHash(gfg));
In this example:
- split(''): This converts the string into an array of characters.
- reduce(): The reduce() method loops through the array, performing a cumulative operation on each character. The operation here is to add the character's ASCII value to an accumulator.
- char.charCodeAt(0): This gets the ASCII code of each character.
- Accumulator (acc): This starts at 0 and keeps adding the ASCII values of each character.
4. Using SHA-256 algorithm
The crypto module in Node.js allows developers to work with cryptographic operations like hashing. The createHash() method is commonly used to create a hash of a given input using algorithms like SHA-256.
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
5. Using the crypto.subtle API (Browser Environment)
The crypto.subtle API is built into modern browsers and provides a way to perform cryptographic operations like hashing. Here is how you can generate a SHA-256 hash in the browser using crypto.subtle
JavaScript
async function hashString(inputString) {
const encoder = new TextEncoder();
const data = encoder.encode(inputString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
return hashHex;
}
hashString("Hello, World!").then(hash => {
console.log("Hash: " + hash);
});
Output
Hash: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda7c8a660e3a1b3cfbf1b
In this example
- The TextEncoder converts the string into a byte array.
- The crypto.subtle.digest() method performs the SHA-256 hashing.
- The result is a ArrayBuffer, which we convert to an array of bytes and then to a hexadecimal string.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read