I need to format an input text like this: 2342452-1. After typing seven numbers I need to add a dash (-) and then a number again. Is there a simple way of doing this in javaScript?
Asked
Active
Viewed 649 times
-1
-
Yes, using either a search engine like Google or the search field from SO `(:` – Ele Sep 23 '18 at 01:07
-
Take a look at [input-mask](https://github.com/RobinHerbots/Inputmask), this helps me a lot on putting masks in input fields. – Shidersz Sep 23 '18 at 01:10
1 Answers
1
You can check the length and use indexOf
to find if this string contains a '-'
function maskinput(e) {
if (e.target.value.length > 7 && e.target.value.indexOf('-') === -1) {
let substring1 = e.target.value.slice(0, 7),
substring2 = e.target.value.slice(7, e.target.value.length);
e.target.value = substring1 + '-' + substring2;
}
}
<input type='text' onkeyup='maskinput(event)'>

brk
- 48,835
- 10
- 56
- 78