0

How can I put a hyphen symbol (-) after the user types three numbers, then again after other three numbers. Like this:

719-646-636

It should be done automatically, in javascript.

Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36

2 Answers2

0

use below code

const str = 'ababab';

const result = str.replace(/.{3}/g, '$&-');

Source : https://bobbyhadz.com/blog/javascript-insert-character-every-n-characters#:~:text=To%20insert%20a%20character%20after,characters%20plus%20the%20provided%20replacement.

Madhav
  • 317
  • 2
  • 12
0

I think this is a good use case for the plugin jquery-inputmask.

Take a look at the documentation, there are plenty of options.

You can get your desired behavior in a one-liner javascript (plus workable copy/paste and disabling non-numeric characters).

$("input[name=my-numeric-value]").inputmask()
input {
  font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/jquery.inputmask.bundle.js"></script>

<input type="text" name="my-numeric-value" placeholder="xxx-xxx-xxx" data-inputmask="'mask': '999-999-999'"/>
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36