Fill left zeros in Javascript

Asked

Viewed 16,703 times

13

I need to insert zeros left into a field input text. Whereas this field might even be 5 characters + one check digit That is, I need Javascript to fill in zeros to the left according to what the user type, for example:

123451 = 12345-1
12341 = 01234-1

or

1236 = 00123-6

5 answers

13


You can do a function to correct the value of this input. Something like:

function pad(str, length) {
  const resto = length - String(str).length;
  return '0'.repeat(resto > 0 ? resto : '0') + str;
}

// exemplo de testes
var testes = [1, 10, 100, 1000];
testes.forEach((teste) => {
  var resultado = pad(teste, 3);
  console.log(resultado);
});

Adapted to your case would look like this:

function ajustarInput(str) {
  var adicionar = 6 - str.length;
  for (var i = 0; i < adicionar; i++) str = '0' + str;
  return str.slice(0, 5) + '-' + str.slice(-1);
}

document.getElementById('teste').addEventListener('click', function() {
  var input = document.getElementById('input');
  input.value = ajustarInput(input.value);
});
<input type="text" id="input" />
<button id="teste">Corrigir</button>

This function reads how many characters are missing from the string, and joins zeros. Then separates the last character and inserts a - before returning the new string.

  • 2

    Perfect!! @Rgio needed something practical

10

Just use this operation on string:

("000000"+str).slice(-6,-1)+'-'+("0"+str).slice(-1)


If you want to increment, you can filter before to remove the non-numeric:

str="000000"+str.replace(/\D/g,'');
str=str.slice(-6,-1)+'-'+str.slice(-1);


Demonstration:

document.getElementById('format').addEventListener('click', function () {
    var input = document.getElementById( 'entrada' );
    
    input.value="000000"+input.value.replace(/\D/g,'');
    input.value=input.value.slice(-6,-1)+'-'+input.value.slice(-1);
});
<input type="text" id="entrada">
<button id="format">Formatar</button><br>

  • 1

    nãssa, champion this here and +1+ by fiddle stack . . . with forgiveness of Sergio’s magic, Checkmark might as well come here

  • ok was the implementation that did not work @brasofilo the code is good my implementation that did not roll.

  • 1

    The implementation of the comment here also did not happen, @Ivan :D renan’s response :))

6

Just do something like:

var foo; // preencha esta variável com o seu texto.
/* sério, preencha foo. */
foo += ""; // só por paranóia. Se foo não era string até aqui, depois desta linha será.

while (foo.length < 5) {
    foo = "0" + foo;
}
// agora coloque foo de novo na caixa de texto.

If the text has five characters or more, it skips the loop. Otherwise, the code will concatenate zeros to the left until the string is five characters long.

Note that this code works for the text to the left of your checker digit. You must then concatenate the checker digit at the end of the result.

  • I understood the logic but it didn’t work your function @Renan

  • The function works beauty, @Ivan, probably it was its implementation that bugged ;)

  • Works, works, if the content of foo comes as a string beforehand. If a number (most common cases to simulate a zerofill of this type) it fails because the Number object does not have a property length. Nothing that a foo = foo.toString(); before the loop does not resolve.

  • @Brunoaugusto edited the answer to take this into account, thanks :)

  • I would change to foo.toString(). At least it doesn’t smell like skulking.

2

I believe that already resolves:

const n = '1236'
(n.slice(0, -1) + '-' + n.slice(-1)).padStart(7, '0')

For a more detailed example:

const inputNumber = document.getElementById('number')
inputNumber.addEventListener('keyup', e => handleDigits(e.currentTarget))
handleDigits(inputNumber)

function handleDigits(field) {
  let n = field.value.replace(/[^\d]/, '').replace(/^0+/, '')
  n = n || '0'
  
  const digitsBeforeTheHyphen = n.slice(0, -1)
  const lastDigit = n.slice(-1)
  const digitsWithHyphen = digitsBeforeTheHyphen + '-' + lastDigit
  const zeroesIncluded = digitsWithHyphen.padStart(7, '0')
  
  field.value = zeroesIncluded
}
<input type="text" id="number" value="1236">

0

Has the implementation PHP str_pad() Javascript made by PHP.JS staff:

function str_pad(input, pad_length, pad_string, pad_type) {
  //  discuss at: http://phpjs.org/functions/str_pad/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Michael White (http://getsprink.com)
  //    input by: Marco van Oort
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  //   example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
  //   returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
  //   example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
  //   returns 2: '------Kevin van Zonneveld-----'

  var half = '',
    pad_to_go;

  var str_pad_repeater = function(s, len) {
    var collect = '',
      i;

    while (collect.length < len) {
      collect += s;
    }
    collect = collect.substr(0, len);

    return collect;
  };

  input += '';
  pad_string = pad_string !== undefined ? pad_string : ' ';

  if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
    pad_type = 'STR_PAD_RIGHT';
  }
  if ((pad_to_go = pad_length - input.length) > 0) {
    if (pad_type === 'STR_PAD_LEFT') {
      input = str_pad_repeater(pad_string, pad_to_go) + input;
    } else if (pad_type === 'STR_PAD_RIGHT') {
      input = input + str_pad_repeater(pad_string, pad_to_go);
    } else if (pad_type === 'STR_PAD_BOTH') {
      half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
      input = half + input + half;
      input = input.substr(0, pad_length);
    }
  }

  return input;
}

document.getElementById( 'test' ).innerHTML = str_pad( 10, 5, 0, 'STR_PAD_LEFT' );
<div id="test"></div>

The interesting thing about this function, besides the complete parameterization (not only of the input string) is that it considers other scenarios unnecessary to the topic but useful in other circumstances.

  • 2

    Vish... O snippet even works, but the post got very ugly >.<

Browser other questions tagged

You are not signed in. Login or sign up in order to post.