Generate a Hash from string in Javascript

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

    I needed a similar function (but different) to generate a unique-ish ID based on the username and current time. So:

    window.newId = ->
      # create a number based on the username
      unless window.userNumber?
        window.userNumber = 0
      for c,i in window.MyNamespace.userName
        char = window.MyNamespace.userName.charCodeAt(i)
        window.MyNamespace.userNumber+=char
      ((window.MyNamespace.userNumber + Math.floor(Math.random() * 1e15) + new Date().getMilliseconds()).toString(36)).toUpperCase()
    

    Produces:

    2DVFXJGEKL
    6IZPAKFQFL
    ORGOENVMG
    ... etc 
    

    edit Jun 2015: For new code I use shortid: https://www.npmjs.com/package/shortid

提交回复
热议问题