javascript - Regex phone number live formatting -


in angularjs, need format phone numbers while being typed. don't want use library should straight forward.

the format need : 99 99 99 99 99

var phone = tel.replace(/\d*(\d{2})\d*(\d{2})\d*(\d{2})\d*(\d{2})\d*(\d{2})\d*/, '$1 $2 $3 $4 $5'); 

but formats number once has been typed. how can make regular expression work when number not yet complete ?

i tried :

var phone = tel.replace(/\d*(\d{2})\d*(\d{0,2})?\d*(\d{0,2})?\d*(\d{0,2})?\d*(\d{0,2})?\d*/, '$1 $2 $3 $4 $5'); 

but adding non required spaces.

you want "straight forward", yet you're artificially constraining problem (by forcing solution regex) when pure regex poor solution problem.

why? because problem involves conditionally adding new characters output (the spaces) may not appear in input, shouldn't added - .replace() isn't equipped deal that.

you'd better off using combination of regex , other javascript handle conditional formatting:

// digits string var phonedigits = tel.replace(/\d/g, ""); // join first up-to-5 pairs of digits spaces, // allowing singleton if number of digits odd. var phone = (phonedigits.match(/\d\d?/g) || []).slice(0,5).join(" "); 

(the || [] bit avoids case match returns null when no digits present.)


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -