Mona Coder
Mona Coder

Reputation: 6316

Inserting character to input as phone number

How can I fix this code to apply the - only after 3 first number, so the output looks like

778-2299

not 778-229-9 as you can see the code is adding the - after every 3 digits

$('.phonenumber').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,3}', 'g')).join("-");
  }
  $(this).val(foo);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="phonenumber" maxlength="8"/>

Upvotes: 0

Views: 604

Answers (3)

Heretic Monkey
Heretic Monkey

Reputation: 12114

I'm not sure why regex is required. Just use good old substring.

I also changed it to use the input event, as it is more consistent in when it fires (after the value has been updated)

$('.phonenumber').on('input', function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if (foo.length === 7) {
    foo = `${foo.substring(0,3)}-${foo.substring(3)}`;
    // or if you're kickin it old skool:
    // foo = foo.substring(0,3) + "-" + foo.substring(3);
  }
  $(this).val(foo);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="phonenumber" maxlength="8"/>

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42044

You can use:

.replace(regexp|substr, newSubstr|function): ...method returns a new string with some or all matches of a pattern replaced by a replacement.

$('.phonenumber').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.replace(/(\d{3})(\d*)/, '$1-$2');
  }
  $(this).val(foo);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="phonenumber" maxlength="8"/>

Upvotes: 2

IceMetalPunk
IceMetalPunk

Reputation: 5556

Don't use the g flag? That means "globally search for the matching pattern", but you only want it to match the first, so you don't want that flag.

Upvotes: 0

Related Questions