M Haase
M Haase

Reputation: 87

Pad a string using random numbers to a fixed length using javascript

I am looking to pad a string with random numbers to meet a certain length (i.e. 10 characters). For example:

HAM --> HAM3481259 or TURKEY --> TURKEY6324

I've tried some JavaScript functions but I either had too many or no numbers at all. Any suggestions would be greatly appreciated.

Upvotes: 1

Views: 807

Answers (2)

fedeisas
fedeisas

Reputation: 2023

Slightly faster version of Nina's answer:

function padRandom(string, length) {
    random_number_length = length - string.length;

    if (random_number_length > 0) {
        string += randomFixedInteger(random_number_length);
    }

    return string
}

function randomFixedInteger(length) {
    return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}

console.log(padRandom('HAM', 10));
console.log(padRandom('TURKEY', 10));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386746

You could check the length and add a random digit, if smaller than the wanted length.

function padRandom(string, length) {
    while (string.length < length) {
        string += Math.floor(Math.random() * 10);
    }
    return string;
}

console.log(padRandom('HAM', 10));
console.log(padRandom('TURKEY', 10));

Upvotes: 3

Related Questions