Javascript function for zeros on the left with MVC 5

Asked

Viewed 3,446 times

5

I have a loop inside my cshtml file. This loop has a variable i and I use it to compose a name according to her position in the loop, like txtNome1, txtNome2, txtNome3 and so on.

I need to make the variable composed with zeros on the left so that the name smaller than 10 looks like this: txtNome01, txtNome02, txtNome03 and so on.

How to do this inside the loop in the file cshtml? My problem is how to use it. See below part of my for(loop). I need to compose the variables that will complete the name.

    string 
        nm,dia,mes,ano,sexo,numpassaporte,
        diavalidade, mesvalidade,
        anovalidade, paisemissao = "";

    for (int i = 1; i < 3; i++)
    {
        nm            = "txtNome" + i;
        dia           = "txtDia" + i;
        mes           = "txtMes" + i;
        ano           = "txtAno" + i;
        sexo          = "txtSexo" + i;
        numpassaporte = "txtPassaporte" + i;
        diavalidade   = "txtDiaVal" + i;
        mesvalidade   = "txtMesVal" + i;
        anovalidade   = "txtAnoVal" + i;
        paisemissao   = "txtPaisEmissao" + i;

I spoke Javascript, but it can be anything, as long as it’s not in code Behind to give more performance to the site.

  • If you found your answer mark one of them as a solution to your problem..

4 answers

3

You can use the method String.padStart() to fill your numbers with zeroes on the left.

"2".padStart(5, 0);  // "00002"
"123".padStart(8, 0);  // "00000123"

Case to compatibility is a problem, the documentation on MDN has an example of polyfill, or you can see this answer of Soen who have a function that makes the padding. See the code:

function lpad(num, size) {
    let s = num + "";
    while (s.length < size) s = "0" + s;
    return s;
}

If you know that the number will not exceed N digits, you could also do:

function pad(num, size) {
    let s = "000000000" + num;
    return s.substr(s.length-size);
}

0

If the rule is to have only 2 digits, you can do so:

var sufixo = i < 10 ? "0" + i : i;

and then concatenate with variable names:

nm            = "txtNome" + sufixo;
dia           = "txtDia" + sufixo;
mes           = "txtMes" + sufixo;
ano           = "txtAno" + sufixo;
sexo          = "txtSexo" + sufixo;
numpassaporte = "txtPassaporte" + sufixo;
diavalidade   = "txtDiaVal" + sufixo;
mesvalidade   = "txtMesVal" + sufixo;
anovalidade   = "txtAnoVal" + sufixo;
paisemissao   = "txtPaisEmissao" + sufixo;

With all this inside the for

0

Use the function below (source) to fill a string for a certain size with another string:

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

And inside your loop, apply the str_pad function to complete with zeros on the left:

    for (int i = 1; i < 3; i++)
    {
        i_pad = str_pad(i, 2, '0', 'STR_PAD_LEFT');
        nm            = "txtNome" + i_pad;
        dia           = "txtDia" + i_pad;
        (...)

0

In javascript you can use slice provided you know number of characters

nm = 'txtNome' + ("0"+i).slice(-2); // txtNome01

I made an example in jsfiddle

One approach I would also take is:

Number.prototype.leadingZeros = function (n) {
  var z = n - this.toString().length + 1;
  return Array(z<0?0:z).join("0") + this;
}

That can be used like this:

nm = 'txtNome' + i.leadingZeros(2); // txtNome01

An example in jsfiddle

In c# you can use something like this:

public static string leadingZeros(int n, int s){
    return n.ToString(String.Concat(Enumerable.Repeat("0", s<0?0:s).ToArray()));
}

ex:

 nm = "txtNome" + leadingZeros(i, 2);

or

 nm = "txtNome" + i.ToString("00");

Browser other questions tagged

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