Home > Web Front-end > JS Tutorial > How Can I Efficiently Hash Strings in JavaScript?

How Can I Efficiently Hash Strings in JavaScript?

DDD
Release: 2024-12-06 19:49:16
Original
783 people have browsed it

How Can I Efficiently Hash Strings in JavaScript?

Hashing Strings in Javascript

In the realm of JavaScript, the need arises to transform strings into a compact form of representation known as a hash. Unlike server-side languages, JavaScript presents a unique challenge for this task.

Fortunately, JavaScript provides a solution through the use of the hashCode() method. This method, when applied to a string, generates a unique hash value that serves as a fingerprint for the string.

Example

Implementation:

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:

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

Output:

revenue 557163167
Copy after login

The above is the detailed content of How Can I Efficiently Hash Strings in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template