Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Hash from string in Javascript

I need to convert strings to some form of hash. Is this possible in JavaScript?

I'm not utilizing a server-side language so I can't do it that way.

like image 507
Freesnöw Avatar asked Sep 30 '11 21:09

Freesnöw


People also ask

How do you make hash out of string?

In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more.

How do you hash data in JavaScript?

You can implement a Hash Table in JavaScript in three steps: Create a HashTable class with table and size initial properties. Add a hash() function to transform keys into indices. Add the set() and get() methods for adding and retrieving key/value pairs from the table.

Is there a hash function in JavaScript?

Definition of JavaScript hash() Hash function in Javascript is any function that takes input as arbitrary size data and produces output as fixed-size data. Normally, the returned value of the hash function is called hash code, hash, or hash value.


1 Answers

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

Source: http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/

like image 76
esmiralha Avatar answered Sep 24 '22 02:09

esmiralha