13

I found this answer Is there any way to generate the same UUID based on the seed string in JDK or some library? but this is the java way.

I need to the same, but in javascript, i can use any npm module or any library or custom function.

You can use UUID this way to get always the same UUID for your input String:

String aString="JUST_A_TEST_STRING";
String result = UUID.nameUUIDFromBytes(aString.getBytes()).toString();

Community
  • 1
  • 1
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50
  • i tried to find all the libraries avail at npmrc, but no one actually does the trick, I just want to create a hash out of the input string and covert that to uuid format – Abhijeet Ahuja Feb 01 '17 at 05:18
  • what's wrong with [UUID.fromBytes](https://www.npmjs.com/package/uuid-js)? – Kos Feb 01 '17 at 05:29
  • @Kos https://runkit.com/587dbce018e01000132892ea/5891724b4e76630014221ea8 i tried, but isn't working – Abhijeet Ahuja Feb 01 '17 at 05:47

3 Answers3

23

Current accepted solution will only work in NodeJS environment per github page of uuid-1345:

Un-Features:

  • Does not work in the browser due to the use of NodeJS's crypto module.

If you are looking for a solution that will work in the browser, you should use a more popular uuid library.

const uuidv5 = require('uuid/v5');

// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'

The UUID will stay consistent as long as you pass it the same namespace.

Hope that helps.

Community
  • 1
  • 1
user2961443
  • 339
  • 3
  • 9
  • the uuid lib has over a 32millon weakly downloads so this is definitely a preferable solution – dimaqw Dec 02 '20 at 15:20
8

Easiest way:

const getUuid = require('uuid-by-string')

const uuidHash = getUuid('Hello world!')
// d3486ae9-136e-5856-bc42-212385ea7970

https://www.npmjs.com/package/uuid-by-string

trialsin
  • 81
  • 1
  • 2
2

Finally this came to my rescue

var UUID = require('uuid-1345');

UUID.v5({
    namespace: UUID.namespace.url,
    name: "test"
});
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50