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
Patricia ArquetteOriginal
2024-12-04 19:12:101074browse

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;
};

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

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

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!

Statement:
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