Fill in leading zeros in JavaScript

12

I need to insert leading zeros in a input text field. Since this field can be up to 5 characters + a checker digit That is, I need to fill in the leading zeros according to what the user types, for example:

123451 = 12345-1
12341 = 01234-1

or

1236 = 00123-6
    
asked by anonymous 18.10.2014 / 00:20

4 answers

12

You can make 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 the string is missing, and adds zeros to it. Then it separates the last character and inserts a - before returning the new string.

    
18.10.2014 / 00:48
8

Just use this operation in string :

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


If you want to increment, you can make a filter before, to remove non-numeric ones:

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>
    
18.10.2014 / 04:18
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 is five characters or more, it skips the loop. Otherwise, the code will concatenate leading zeros until the string is five characters long.

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

    
18.10.2014 / 00:27
0

You also have implementation in PHP's PHP str_pad () JavaScript done 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 full parameterization (not just the input string) is that it considers other scenarios unnecessary to the topic but useful in other circumstances.

    
20.10.2014 / 19:57