user5402143
user5402143

Reputation:

add a dash to a specific digits entered by the user

I did find this function in jQuery that add a dash after very four numbers, but I would like to add a dash to a number entered by the user with the follow format:

1234-1234556-123-1

but I could manage to get it, could you please help me, this is the jQuery function that formats the follow: 1234-1234-1234-1

$('.creditCardText').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if ((foo.length > 0) && (foo.length < 14)) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
  }
  $(this).val(foo);
}); 

Upvotes: 1

Views: 218

Answers (2)

Jeff B
Jeff B

Reputation: 30099

You need to use parenthetical matching groups. Put the pattern in parenthesis. This will return an array with the whole match, followed by the parenthetical matches, followed by some match info. So, you have to slice out array elements 1-4, and then join them with dashes. Because some of the matches may be empty, you can clean up with another replace that removes trailing dashes:

Edit: You could also remove all non-numeric characters, instead of just hyphens. (See second line)

$('.creditCardText').keyup(function() {
  var foo = $(this).val().replace(/\D/g, ""); // remove non-numerics
  if ((foo.length > 0) && (foo.length < 16)) {
    foo = foo.match(new RegExp('(\\d{1,4})(\\d{0,7})(\\d{0,3})(\\d?)')).slice(1,5).join("-").replace(/\-+$/, '');
  }
  $(this).val(foo);
}); 

Demo: https://jsfiddle.net/oohfksjd/

Upvotes: 4

Todor Simeonov
Todor Simeonov

Reputation: 806

It is more RegExp issue, not JavaScript.

RegExp('(.{1,4})(.{1,7})(.{1,3})(.{1,1})', 'g')

Upvotes: -1

Related Questions