Mit Javascript einen Hash aus einem String generieren
<div>
<input type="text" id="myString">
<button onClick="hash()">
Generate Hash
</button>
</div>
<div>
<span>Result: </span>
<span id="myHash"></span>
</div>
const hash = () => {
const myString = document.getElementById('myString').value;
let myHash = myString.hashCode();
document.getElementById('myHash').innerHTML = myHash;
}
// as prototype method
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
// alternative: as function
hashCode = (s) => {
return s.split('').reduce( (a, b) => {
a = (( a << 5 ) - a ) + b.charCodeAt(0);
return a & a;
}, 0);
}