Generate a Hash from string in Javascript

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

    Based on accepted answer in ES6. Smaller, maintainable and works in modern browsers.

    function hashCode(str) {
      return str.split('').reduce((prevHash, currVal) =>
        (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
    }
    
    // Test
    console.log("hashCode(\"Hello!\"): ", hashCode('Hello!'));

    EDIT (2019-11-04):

    one-liner arrow function version :

    const hashCode = s => s.split('').reduce((a,b) => (((a << 5) - a) + b.charCodeAt(0))|0, 0)
    
    // test
    console.log(hashCode('Hello!'))

提交回复
热议问题