3

I am trying to write a regex for US phone numbers where user can enter the number and dash comes automatically. But here the drawback is if user enters "123" and then "-" the regex breaks and instead of 123-456-7890 it becomes 123-4567890 Here is the regex code:

  $('#AccountFrm_telephone').attr('maxlength', '12');

$('#AccountFrm_telephone').keyup(function(){
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "$1-$2-$3"));
});

Maybe There is something that we add in regex so that user can not type dash?

8
  • this part (\d)+ should be (\d+) Commented Feb 23, 2017 at 17:05
  • @Nullman No thats not working :( Commented Feb 23, 2017 at 17:08
  • i ave put your string into var x and the following worked fine x.replace(/^(\d{3})(\d{3})(\d+)$/, "$1-$2-$3") Commented Feb 23, 2017 at 17:10
  • I tried it but it takes dash "-" after 3 number if user enters "-" then breaks the regex still Commented Feb 23, 2017 at 17:13
  • ah, then like the removed post suggested, use this: /^(\d{3})-?(\d{3})-?(\d+)$/, "$1-$2-$3" the ? notes 0 or 1 times Commented Feb 23, 2017 at 17:14

3 Answers 3

1

for completes: you have 2 issues first this part (\d)+ should be (\d+) or you wont capture the last group on numbers correctly. the second part is that you aren't handling possible dashes in the input, so try something like:

.replace(/^(\d{3})-?(\d{3})-?(\d+)$/, "$1-$2-$3")

the question marks (?) denote 0 or 1 times, meaning the user can input the dashes if he wants

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe try the following:

$('#AccountFrm_telephone').attr('maxlength', '12');

$('#AccountFrm_telephone').keyup(function(){
    $(this).val($(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));
});

Comments

1

Try this:

$("#input1").on('keyup', e => {
    e.target.value = e.target.value.replace(/(\d{3})-?(\d{3})-?(\d+)/, '$1-$2-$3')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.