0

I need to change field dynamic and set format with this code i a formatting my zip code its text come from server end like

123456789

and this jQuery method change this value format 1234-56789

var ZIptext = $("#ZipLabel").text();
    var reformat = ZIptext.replace(/(\d{5})/g, function (match) {
        return match + "-";
    });
    $("#ZipLabel").text(reformat.replace(/\-$/, ""))

but know i am facing problem i need to change format of my fax number

3453454354 

and it should be like

345-345-4354 

So can someone help me

Coder
  • 240
  • 2
  • 4
  • 20

3 Answers3

2

Do it with capturing group regex

var res = '3453454354'.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');

document.write(res);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

This question is similar to this one here.

You can do this using:

'345345345'.replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
Community
  • 1
  • 1
Sahil Lakhwani
  • 108
  • 2
  • 11
1

Here's a function to do it generically.

The first argument is the input string, the second is the separator character, and the third is an array of lengths to separate the input with. You can specify a '*' as the last argument as well.

function separate(_input, _separator, _lengths) {
  var output = [], i = 0;
  for(i=0; i<_lengths.length; i++) {
    if(_input.length <= _lengths[i] || _lengths[i] === '*') {
      output.push(_input);
      break;
    }
    output.push(_input.substr(0, _lengths[i]));
    _input = _input.substr(_lengths[i]);
  }
  return output.join(_separator);
}

Usage examples:

separate('3453454354', '-', [3, 3, 4]); // returns "345-345-4354"

separate('3453454354', '-', [4,'*']); // returns "3453-454354"
techfoobar
  • 65,616
  • 14
  • 114
  • 135