Generate a Hash from string in Javascript

前端 未结 22 977
不知归路
不知归路 2020-11-22 03:34

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.

22条回答
  •  孤街浪徒
    2020-11-22 04:35

    I have combined the two solutions (users esmiralha and lordvlad) to get a function that should be faster for browsers that support the js function reduce() and still compatible with old browsers:

    String.prototype.hashCode = function() {
    
        if (Array.prototype.reduce) {
            return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);   
        } else {
    
            var hash = 0, i, chr, len;
            if (this.length == 0) return hash;
            for (i = 0, len = this.length; i < len; i++) {
            chr   = this.charCodeAt(i);
            hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
            }
            return hash;
        }
    };
    

    Example:

    my_string = 'xyz';
    my_string.hashCode();
    

提交回复
热议问题