1

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.

2
  • What are you having trouble with here? What part of this are you stuck on? What have you tried? What do you mean by "tried some JavaScript functions"? Commented Apr 10, 2017 at 21:38
  • If you need to figure out how many characters you need to pad, you can do 10 - str.length (or 10 - (str.length % 10) after checking if str.length % 10 > 0). Commented Apr 10, 2017 at 21:39

2 Answers 2

3

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));

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

4 Comments

What if I wanted to throw in padding with white space to this function? I know it can be done but I am inexperienced with functions but am trying to learn based on examples!
then add the space instead of Math.floor(Math.random() * 10)
how about making it leading so that all of the existing characters are to the right?
i suggest to ask a new question. does any of the here given answers answers your question? you could have here a look, too: stackoverflow.com/help/someone-answers
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.