Home > OS >  jQuery REGEX add automatically space
jQuery REGEX add automatically space

Time:01-11

I may have a little stupid question, but I am wondering how to make field to have space after two characters, and after that to have space after every 3 characters, for example:

99 999 999 999

I used this code:

  $('#form-field-indentification_number').keyup(function() {
      
  var indent = $(this).val().split(" ").join(""); // remove hyphens

  if (indent.length > 2 && indent.length < 4 ) {
    indent = indent.match(new RegExp('.{1,2}', 'g')).join(" ");
  }
  
  if (indent.length > 5 ) {
    indent = indent.match(new RegExp('.{1,3}', 'g')).join(" ");
  }
  
  $(this).val(indent);

But still can't handle it :(

Any help will be appreciated! Thanks

CodePudding user response:

I think I understand that you have a string of contiguous digits like 99999999999 and you would like to insert space every third group from the right.

You can accomplish that with a regex replace where you search with

(\d{1,3})(?=(\d{3}) (\D|$))

and replace with $1 .

The first part of the regex, (\d{1,3}), captures one to three digits into group 1. The rest is a lookahead whose first part, (?=(\d{3}) forms one or more groups of exactly 3 digits and whose last part (\D|$)) anchors the scan to the rightmost part of the digits.

enter image description here

  • Related