Home > Web Front-end > JS Tutorial > How Can I Generate String Hashes in JavaScript Without Server-Side Code?

How Can I Generate String Hashes in JavaScript Without Server-Side Code?

Patricia Arquette
Release: 2024-12-04 19:12:10
Original
1042 people have browsed it

How Can I Generate String Hashes in JavaScript Without Server-Side Code?

Hash Generation from Strings in Javascript

Question:
Can I convert a string into a hash format using Javascript without resorting to server-side languages?

Answer:
Yes, Javascript provides the ability to generate hashes from strings through a modified version of the String prototype.

Implementation:
The following code snippet demonstrates how to extend the String prototype to incorporate a hash function:

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;
};
Copy after login

Usage:
With this modified prototype, you can now generate hashes from strings as follows:

const str = 'revenue'
console.log(str, str.hashCode())
Copy after login

This will output the original string followed by its generated hash code.

The above is the detailed content of How Can I Generate String Hashes in JavaScript Without Server-Side Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template