Generate a Hash from string in Javascript

前端 未结 22 979
不知归路
不知归路 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:24

    If it helps anyone, I combined the top two answers into an older-browser-tolerant version, which uses the fast version if reduce is available and falls back to esmiralha's solution if it's not.

    /**
     * @see http://stackoverflow.com/q/7616461/940217
     * @return {number}
     */
    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);              
        } 
        var hash = 0;
        if (this.length === 0) return hash;
        for (var i = 0; i < this.length; i++) {
            var character  = this.charCodeAt(i);
            hash  = ((hash<<5)-hash)+character;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }
    

    Usage is like:

    var hash = "some string to be hashed".hashCode();
    

提交回复
热议问题