Home > Blockchain >  How to add a separator character between each three numbers in an input field?
How to add a separator character between each three numbers in an input field?

Time:08-08

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.

CodePudding user response:

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'"/>

CodePudding user response:

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 insert a character after,characters plus the provided replacement.

  • Related