0

I need to pass a string with at least has a length of 10. How do I add 0's to fill the remaining blank spaces so it will always have a length of 10?

This is what I tried but does not work as expected.

var passString = "Abcdefg";
if (passString.length<10){
      var len = passString.length;
      var missing = 10-len;
      passString = passString + Array(missing).join("0")
}
Fergoso
  • 1,584
  • 3
  • 21
  • 44

3 Answers3

1

please try below code

var passString = "Abcdefg";
if (passString.length<10){
      var len = passString.length;
      var missing = 10-len;
      passString =passString+  new Array(missing + 1).join("0");
}

thanks

Ripun
  • 210
  • 5
  • 16
1

You can do it in one line (I love giving one liners)

passString = (passString + Array(11).join('0')).substr(0,Math.max(10,passString.length))
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
1

Concat zeros to the end of the string and use slice or substring or substr.

var passString = "ABC";
var fixed = (passString + "0000000000").slice(0,10);
console.log(fixed);

Based on comment, I skipped the if, but you can just do a basic if

var passString = "ABC";
var fixed = passString;
if (passString.length<10) {
    fixed = (passString + "0000000000").slice(0,10);
}
console.log(fixed);

or ternary operator

var passString = "ABC";
var fixed = passString >=10? passString : (passString + "0000000000").slice(0,10);
console.log(fixed);

or just override the original with an if

var passString = "ABC";
if (passString.length<10) {
    passString = (passString + "0000000000").slice(0,10);
}
console.log(passString);
epascarello
  • 204,599
  • 20
  • 195
  • 236