Kode_12 Kode_12 - 11 months ago 55
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.
} else return sQuery

Answer Source


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


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