Kunal Rajput
Kunal Rajput

Reputation: 794

How to insert space after 2 and then 3 characters in html input field?

I am trying to create mobile number input field , when customer inputs mobile number in field automatically space should come in this format 11 111 11111 (space after two characters and then after 3 characters).

I found one solution but it is for space after every 4 digits https://jsfiddle.net/shanks25/ob4zg7rL/1/

Upvotes: 0

Views: 957

Answers (3)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Or, as a one-liner:

document.querySelector('input').onkeyup=ev=>
  ev.target.value=ev.target.value
    .replace(/ /g,'')
    .replace(/^(.{5})/,"$1 ")
    .replace(/^(.{2})/,"$1 ");
<input type="text">

Upvotes: 1

Asutosh
Asutosh

Reputation: 1828

I have added @priyadarshi kumar's formula to complete the given fiddle, please check below fiddle:

$('.creditCardText').keyup(function() {

  var foo = $(this).val().split(" ").join(""); // remove hyphens

  if (foo.length < 6) {
    foo = foo.replace(/^(.{2})(.*)$/, "$1 $2");
  } else if (foo.length >= 6) {
    console.log("here");
    foo = foo.replace(/^(.{2})(.{3})(.*)$/, "$1 $2 $3");
  }

  $(this).val(foo);
});

https://jsfiddle.net/p4vcf7ax/1/

Upvotes: 0

priyadarshi kumar
priyadarshi kumar

Reputation: 192

This will solve your problem.

var result = "1111111111".replace(/^(.{2})(.{3})(.*)$/, "$1 $2 $3");
console.log(result);

Upvotes: 2

Related Questions