Phone number regular expression
Format phone number for normal and toll free number
HTML
<div style="background:#ddd; position:relative; width:90%; padding:20px;">
<p>Regular expression</p>
<!-- INPUT -->
<input id="assure_telephone" placeholder="Phone number" name="assure_telephone" maxlength="25" type="text" />
<p><b>Expected results</b>
<br/>111-222-3333
<br/>111-222-3333 #44444</p>
<hr/>
<p><b>Problems</b></p>
<ol>
<li>If the number is not long enough, it might not work</li>
<li>If we get a number without Ext. the # will still display</li>
<li>If we type a toll-free number, it won't display correctly</li>
</div>
JavaScript
$('#assure_telephone').bind('change', function(){
// Delete all caracters and specials caraters except numbers
telephone_user = $('#assure_telephone').val().replace(/[^0-9]/g, '');
// Format the new phone number
telephone_user_regex = telephone_user.replace(/(\d{3})(\d{3})(\d{4})(\d{0,5})/, "$1-$2-$3 #$4");
$('#assure_telephone').val(telephone_user_regex);
});