Sebastian
Sebastian

Reputation: 149

Formatting input field with periods

I am trying to format fields so that integers entered into the input are preformatted into a specific format.

Currently I have the included JQuery which formats the entered string into xx.xx.xx.xx, How would I force the format to x.xx.xx.xxx and add a limit of 8 integers?

$('.versionNum').keyup(function() {
  var foo = $(this).val().split(".").join(""); // remove periods
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,2}', 'g')).join(".");
  }
  $(this).val(foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="versionNum" />

Upvotes: 2

Views: 574

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

I don't think using a regular expression to construct the output is the most readable choice - it'd be a bit complicated and hard to read. Instead, once you have a string of numbers, slice each section you need, then filter by Boolean (to remove empty strings) and join by dots:

$('.versionNum').keyup(function() {
  const nums = $(this).val().replace(/\D/g, '');
  const n0 = nums[0];
  const n1 = nums.slice(1, 3);
  const n2 = nums.slice(3, 5);
  const n3 = nums.slice(5, 8);
  $(this).val(
    [n0, n1, n2, n3].filter(Boolean).join('.')
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="versionNum" />

Regular expression version:

$('.versionNum').keyup(function() {
  const numStr = $(this).val().replace(/\D/g, '');
  const [, ...arr] = numStr.match(/(\d?)(\d{0,2})(\d{0,2})(\d{0,3})/);
  $(this).val(
    arr.filter(Boolean).join('.')
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="versionNum" />

Upvotes: 4

Related Questions