C0deJack
C0deJack

Reputation: 142

Add formatting spaces to number input using regex and jquery ignoring existing spaces

I'm trying to format a phone number input on blur that has to accept spaces (e.g. <input type="text"). I want the number to be in format ##### ### ### but the string could contain numbers and spaces in any order and have spaces at the end and start. Any more than 11 numbers should be added to the end of the string with one trailing space. e.g. ##### ### ### ###########...

Any help would greatly appreciated. Thanks

12345678910 => 12345 678 910
    12345678910    => 12345 678 910
  1 2 3 4 5 6 7 8 9 1 0  => 12345 678 910
12345678910111213 => 12345 678 910 111213

I've tried this but it's not working if there are spaces within the string:

$('#myInput').on('blur', function () {
    $(this).val($(this).val().trim().replace(/(\s+)(\d{5})(\d{3})(\d{3})/, '$2 $3 $4'));
});

Upvotes: 0

Views: 719

Answers (1)

&#201;ric
&#201;ric

Reputation: 575

Do you want something like this?:

function formatNumber(str) {
    document.getElementById("myInput").value = str.replace(/ /g, "").replace(/^(\d{5})(\d{3})(\d{3})(\d*)$/, "$1 $2 $3 $4");
}
<form>
<div>Simply click in this input field, change the number if you want, then click outside.</div>
<input onblur="formatNumber(this.value)" id="myInput" name="phone" value="1 23 45 67890123456" />
</form>

Upvotes: 1

Related Questions