0

I want a pattern like this:- GT-000001. This pattern gets incremented when a new record is inserted.

So I get values from my DB like this:

var pattern = 'GT-';
var init = 00000;
var recordnumber = 1; // This value i get dynamically.

var result = pattern + init + recodnumber;

But I get result = GT-01. I want result to be GT-000001. How to get this result?

Matt
  • 74,352
  • 26
  • 153
  • 180
Anup
  • 9,396
  • 16
  • 74
  • 138
  • 2
    See http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript (dupe?) – Matt Jun 02 '14 at 12:04

3 Answers3

3

The reason you get that result is that you have

var init = 00000;

Note that the zeroes are not in quotes. That is effectively the same as:

var init = 0;

and so when you put it in the string, you get just the one zero.

If you want five zeroes, you need to use a string:

var init = "00000";

If you're trying to zero-pad, in general, this question and its answers that Matt found may be helpful.

But the short version:

var pattern = 'GT-';
var init = "000000"; // Note there are six of these, not five
var recordnumber = 1; // This value i get dynamically.

var result = String(recordnumber);
result = pattern + init.substring(result.length) + result;
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • But when records will increase to 200....the pattern value should be...`GT-000200` – Anup Jun 02 '14 at 12:05
  • @Anup: Yes, that's the general zero-padding thing. I've shown the simple version above, and linked to the question Matt flagged up. – T.J. Crowder Jun 02 '14 at 12:08
3

The below example works for recordnumber upto 6 digits. outputing 'GT-000001', 'GT-000012', or 'GT-123456' based on the value of recordnumber

var pattern = 'GT-';
var recordnumber = 1; // This value i get dynamically.

var result = pattern + ('00000' + recordnumber).slice(-6);
console.log(result);
closure
  • 7,412
  • 1
  • 23
  • 23
  • Oooh, that's tidier, +1. There was some old browser that didn't handle negatives with `slice` right, but [I just verified](http://jsbin.com/yacugaco/1) this works in IE8, so that's plenty good enough for 2014. – T.J. Crowder Jun 02 '14 at 12:17
2

Your init is number type, it is already truncated to 0 on assignment. You need to add leading zeros manually:

function leadzeros(n, size) {
    var s = n+"";
    while (s.length < size) s = "0" + s;
    return s;
}

var pattern = 'GT';
//var init = 00000; // <- here is 'init' is 0 already, so you can drop it
var recordnumber = 1; // This value i get dynamically.

var result = pattern + leadzeros(recodnumber, 5);
Serg Tomcat
  • 812
  • 10
  • 21