format value with javascript

2

I have the following variable:

var teste = "006BC953F26DAC56C51D61";

And I'd like to see it when it looks like this:

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

I'm having problems since it starts with a group of 4 needs and then 5 and so on.

    
asked by anonymous 23.02.2017 / 18:08

2 answers

3

You can do this:

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);
    
23.02.2017 / 18:41
1

Another alternative, only using 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);
    
26.02.2017 / 14:44