format value with javascript

Asked

Viewed 286 times

2

I have the following variable:

var teste = "006BC953F26DAC56C51D61";

and I’d like when to display it to be like this:

console.log(teste); //006B-C953F-26DA-C56C5-1D61

I’m in trouble because it starts with a group of 4 missing and then 5 and so on.

  • 1

    Take a look at this plugin: jQuery Mask. With it you can create your own mask.

  • 1

    It seems that the mask is simple: '0000-00000-0000-00000-0000'

2 answers

3


you can do so:

var format = function (format, text) {  
  var array = text.split("");
  return format.replace(/{(.*?)}/g, function (index) {
    return array.splice(0, index.replace(/\D/g, "")).join("");
  });
};

var texto = format("{4}-{5}-{4}-{5}-{4}", "006BC953F26DAC56C51D61");
console.log(texto);

1

Alternative, only with the use of slice and join.

var teste = "006BC953F26DAC56C51D61";

var formato = [
teste.slice(0,4),teste.slice(4,9),teste.slice(9,13),teste.slice(13,18),teste.slice(18)
].join('-');

console.log(formato);

Browser other questions tagged

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