Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 323
Kode_12 Avatar asked Jan 05 '23 03:01

Kode_12


1 Answers

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:

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: ' + padZeros("1234567890"));
console.log('padZeros: ' + padZeros("123"));
console.log('padZeros: ' + padZeros(""));

Alternate version that doesn't affect strings over your set limit:

function padZerosIfShort(inputString = "", paddedOutputLength = 10) {        
  let inputLen = inputString.length;
  
  // only padded if under set length, otherwise returned untouched
  return (paddedOutputLength > inputLen)
    ? "0".repeat(paddedOutputLength - inputLen) + inputString 
    : inputString;                                            
}

console.log('padZerosIfShort: ' + padZerosIfShort("1234567890", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("123", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("", 5));

It will ultimately depend on your needs how you want to implement this behavior.

like image 196
Jecoms Avatar answered Jan 12 '23 19:01

Jecoms