Kode_12 Kode_12 - 1 month ago 5
jQuery Question

How can I prepend characters to a string using loops?

I have an input field that expects a 10 digit number. If the user enters and submits a number less than 10 digits, the function would simply add a "0" until the inputed value is 10 digits in length.

I haven't really used, or understand how recursive functions really work, but I'm basically looking at an efficient way of doing this. One minor issue I'm having is figuring out how to prepend the "0"s at the beginning of the string rather than appended to the end.

My thinking:

function lengthCheck(sQuery) {
for (var i = 0; i < sQuery.length; i++) {
if (sQuery.length !== 10) {
sQuery += "0";
//I'd like to add the 0s to the beggining of the sQuery string.
console.log(sQuery);
lengthCheck(sQuery);
} else return sQuery
}
}

Answer

Change:

sQuery += "0"; // added at end of string

to:

sQuery = "0" + sQuery; // added at start of string

To remove the for loop/recursion, you could slice out the desired length in one step:

// you could make this more generic to accept input on length of padding / output
function padZeros(sQuery) {
    // the max amount of zeros you want to lead with
    const maxLengthZeros = "0000000000"; 

    // takes the 10 rightmost characters and outputs them in a new string
    return (maxLengthZeros + sQuery).slice(-10); 
}

Simple generic function using ES6 repeat:

// edge case constraints not implemented for brevity
function padZeros(sQuery = "", maxPadding = 10, outputLength = 10) {
        // the max amount of zeros you want to lead with
        const maxLengthZeros = "0".repeat(maxPadding); 

        // returns the "outputLength" rightmost characters
        return (maxLengthZeros + sQuery).slice(-outputLength); 
    }

console.log(padZeros("1234567890"));
console.log(padZeros("123"));
console.log(padZeros(""));