10 examples of 'hash string to integer' in JavaScript

Every line of 'hash string to integer' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
2function hash(string) {
3 string = string == null ? '' : string + '';
4 let hash = 0;
5 if (!string) return '' + hash;
6 const length = string.length;
7 for (let i = 0; i < length; i++) {
8 hash = ((hash << 5) - hash) + string.charCodeAt(i);
9 hash = hash & hash; // Convert to 32bit integer
10 }
11 return (hash).toString(16);
12}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

167function hash(str) {
168 var hashCode = 0;
169 if (str.length === 0) { return hashCode; }
170 for (var i = 0; i < str.length; i++) {
171 var c = str.charCodeAt(i);
172 hashCode = ((hashCode << 5) - hashCode) + c;
173 hashCode = hashCode & hashCode; // Convert to 32-bit integer
174 }
175 return hashCode;
176}
5export function hash(string) {
6 if (typeof string != "string") return 0;
7 let hash = 0;
8 if (string.length === 0) {
9 return hash;
10 }
11 for (let i = 0; i < string.length; i++) {
12 let char = string.charCodeAt(i);
13 hash = ((hash<<5)-hash)+char;
14 hash = hash & hash; // Convert to 32bit integer
15 }
16 return hash;
17}
12function hashString(string) {
13 let hash = 0;
14 for (let i = 0, len = string.length; i < len; i += 1) {
15 hash = (31 * hash + string.charCodeAt(i)) | 0;
16 }
17 return hash;
18}
4export default function hash(str) {
5 return murmurhash2(str, str.length).toString(36)
6}
1export default function hashString(str: string) {
2 return hash(str, str.length).toString(36)
3}
4export function stringHash (str: string): number {
5 let hash = 0;
6
7 for(let i = 0; i < str.length; ++i) {
8 hash = (((hash << 5) - hash) + str.charCodeAt(i)) | 0;
9 }
10
11 return hash;
12}
213function hash(str)
214{
215 var h = 5381;
216 for (var i = 0; i<str.length; i++)
217 h = (h * 37 + str.charCodeAt(i)) >>> 0;
218// h &= 0xffffffff;
219 h = h >>> 0;
220 h &= 0x0000ffff;
221
222 return "0x"+("00000000" + h.toString(16)).substr(-8);
223}
329function stringHash(str) {
330 var hash = 5381,
331 i = str.length;
332
333 while (i) hash = (hash * 33) ^ str.charCodeAt(--i);
334 return (hash >>> 0).toString(36);
335}
77hashString: function hashString(string) {
78 var hash = 0;
79 for (var i = 0; i < string.length; i++) {
80 hash = (hash << 5) - hash + string.charCodeAt(i) & 0xFFFFFFFF;
81 }
82 return hash;
83},

Related snippets