Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format in Javascript?

In C# whenever I wanted to print two digit numbers I've used

int digit=1;
Console.Write(digit.ToString("00"));

How can I do the same action in Javascript ?
Thanks

like image 262
Mohammad Dayyan Avatar asked Jun 02 '11 21:06

Mohammad Dayyan


People also ask

What is the format of string?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.

How do you write a string in JavaScript?

In JavaScript, there are three ways to write a string — they can be written inside single quotes ( ' ' ), double quotes ( " " ), or backticks ( ` ` ). The type of quote used must match on both sides, however it is possible that all three styles can be used throughout the same script.

How do you write backticks in JavaScript?

Note: we can easily use single quotes ( ' ) and double quotes ( " ) inside the backticks ( ` ). Example: var nameStr = `I'm "Alpha" Beta`; To interpolate the variables or expression we can use the ${expression} notation for that.


1 Answers

c# digit.toString("00") appends one zero to the left of digit (left padding). In javascript I use this functon for that:

function zeroPad(nr,base){
  var  len = (String(base).length - String(nr).length)+1;
  return len > 0? new Array(len).join('0')+nr : nr;
}
zeroPad(1,10);   //=> 01
zeroPad(1,100);  //=> 001
zeroPad(1,1000); //=> 0001

You can also rewrite it as an extention to Number:

Number.prototype.zeroPad = Number.prototype.zeroPad || 
     function(base){
       var nr = this, len = (String(base).length - String(nr).length)+1;
       return len > 0? new Array(len).join('0')+nr : nr;
    };
 //usage:
(1).zeroPad(10);   //=> 01
(1).zeroPad(100);  //=> 001
(1).zeroPad(1000); //=> 0001

[edit oct. 2021]

A static es20xx Number method, also suitable for negative numbers.

Number.padLeft = (nr, len = 2, padChr = `0`) => 
  `${nr < 0 ? `-` : ``}${`${Math.abs(nr)}`.padStart(len, padChr)}`;
console.log(Number.padLeft(3));
console.log(Number.padLeft(284, 5));
console.log(Number.padLeft(-32, 12));
console.log(Number.padLeft(-0)); // Note: -0 is not < 0
like image 160
KooiInc Avatar answered Sep 22 '22 23:09

KooiInc