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!