1

I trying to write a script using jQuery, it is suppose to automatically put a space after every numbers. in order to separate a sequence of numbers that user input in an input field. e.g. 4444 4444 4444 4444

$('#creditcardnumber').blur(function(){
  var creditcardnumber= $(this), val = creditcardnumber.val();
  if(val.length > 4)
    creditcardnumber.val(val.slice(0, -4)+' '+val.slice(-4));
})
Mukesh
  • 1,257
  • 11
  • 27
  • where is the script you wrote? – roullie Dec 12 '14 at 08:22
  • "I trying to write a script using jQuery", what it is? – Bharadwaj Dec 12 '14 at 08:22
  • possible duplicate of [How can I insert a character after every n characters in javascript?](http://stackoverflow.com/questions/1772941/how-can-i-insert-a-character-after-every-n-characters-in-javascript) – Abhitalks Dec 12 '14 at 08:35
  • instead of using `blur` use `focusout` event as shown in fiddle http://jsfiddle.net/6wgoe5s8/ – Kartikeya Khosla Dec 12 '14 at 08:39
  • `var buffer = val.substr(0, 4); for (var i = 4, len = val.length; i < len; i += 4) { buffer += ' ' + val.substr(i, 4); }` should work fine (the result will be in `buffer`) – h2ooooooo Dec 12 '14 at 08:57

1 Answers1

0

var number= 4444444444444444;

alert(("" + number).replace(/\B(?=(\d{3})+(?!\d))/g, " "));

$('#creditcardnumber').blur(function(){
    var creditcardnumber = $(this), val = creditcardnumber.val();

    creditcardnumber.val(("" + number).replace(/\B(?=(\d{3})+(?!\d))/g, " "));
})

Here two lookahead assertions use in regex :

  1. one to look for any point in the string that has a multiple of 3 digits in a row after it,

  2. another assertion to make sure that point only has exactly a multiple of 3 digits.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Malitha
  • 1
  • 2