SoFunction
Updated on 2025-03-04

JS regular expression implements the code separated by spaces every four digits

Numbers are separated with spaces every four digits of code:
Share a code instance, which implements the separation of numbers with spaces every four digits.
This effect is very common when filling out a bank card, which is also a very humane measure.

The code example is as follows:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>I</title>
<script src="/jquery/1.9.0/"></script>
<script>
$(document).ready(function () {
 $('#ant').on('keyup mouseout input', function () {
  var $this = $(this);
  var v = $();
  /\S{5}/.test(v) && $((/\s/g, '').replace(/(.{4})/g, "$1 "));
 });
})
</script>
</head>
<body>
<input type="text"  />
</body>
</html>

The above code implements our requirements, and you can refer to the relevant reading for more content.

Related readings:

(1).on() can refer to the detailed explanation of jquery on() binding event handling function.
(2).Keyup event can be found in the jQuery keyup event chapter.
(3) The val() method can be found in the chapter jQuery val() method.
(4). The test() method can refer to the chapter on the regular expression test() function.
(5).replace() can be found in the chapter on the regular expression replace() function.
(6).$1 can be found in the chapter on the regular expression replace() function.
(7). Subexpressions can be found in the chapter on regular expression grouping.