0

i'm new to javascript i need to generate random number using replace it is possible i try

function generateUUID() {
    var dt = new Date().getTime()
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace('/[xy]/g', function (c) {
        var r = (dt + Math.random() * 16) % 16 | 0
        dt = Math.floor(dt / 16)
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
    return uuid
}

this function always return xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx What am i missing ?

2
  • 1
    does the string '/[xy]/g' exist? no ... you want a regular expression ... /[xy]/g Commented Jun 30, 2021 at 10:10
  • 1
    use regular expression format properly /[xy]/g instead of '/[xy]/g' Commented Jun 30, 2021 at 10:14

1 Answer 1

1

You're using a string rather than a RegExp in the replace function, this should be a simple fix, e.g. just change

.replace('/[xy]/g',

to

.replace(/[xy]/g,

function generateUUID() {
    var dt = new Date().getTime()
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (dt + Math.random() * 16) % 16 | 0
        dt = Math.floor(dt / 16)
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
    console.log("uuid",uuid)
    return uuid
}

console.log(generateUUID())

I'd also suggest looking at third-party libraries for this purpose, uuid for example, it uses cryptographically-strong random values.

function generateUUID() {
    return uuid.v4();
}
console.log(generateUUID());
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js" integrity="sha512-UNM1njAgOFUa74Z0bADwAq8gbTcqZC8Ej4xPSzpnh0l6KMevwvkBvbldF9uR++qKeJ+MOZHRjV1HZjoRvjDfNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Terry Lennox
No problem, glad to be of some help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.