Generate a Hash from string in Javascript

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

    Slightly simplified version of @esmiralha's answer.

    I don't override String in this version, since that could result in some undesired behaviour.

    function hashCode(str) {
        var hash = 0;
        for (var i = 0; i < str.length; i++) {
            hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
        }
        return hash;
    }
    

提交回复
热议问题