最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Auto correct phone format input - Stack Overflow

matteradmin5PV0评论

I'm trying to auto format an input on HTML with javascript, and it is almost done, i need the format to be xxx-xxx-xxxx but and I have this code

this.value = this.value.replace(/(\d{3})\-?/g,'$1-');

as youy can see it will just auto format xxx-xxx-xxx but I need to be 4 digits at the end

any sugestions?

I'm trying to auto format an input on HTML with javascript, and it is almost done, i need the format to be xxx-xxx-xxxx but and I have this code

this.value = this.value.replace(/(\d{3})\-?/g,'$1-');

as youy can see it will just auto format xxx-xxx-xxx but I need to be 4 digits at the end

any sugestions?

Share Improve this question edited Apr 9, 2014 at 20:05 kei 20.5k2 gold badges37 silver badges64 bronze badges asked Apr 9, 2014 at 19:57 user3516479user3516479 114 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Try this regexp:

'1234567890'.replace(/(\d{3}(?!\d?$))\-?/g, '$1-'); // 123-456-7890

The part (?!\d?$) is a negative lookahead. It allows regular expression to match three digits only if they are not followed by another number (4th) (but not necessarily ?) at the end of the string $.

So it will not match 789 group because it's followed by 0$.

Or simply : .replace(/(\d{3})(\d{3})(\d{4})\-?/g,'$1-$2-$3');

Sample code to help you out:

var phone = '(555) 666-7777';

// First clean your input
phone = phone.replace(/[^\d]/g, '');
// Check the length of the phone
if(phone.length == 10){
    // Now we can format the phone
    phone = phone.substring(0,3)+'-'+phone.substring(3,6)+'-'+phone.substring(6, 10);
    // Optionally
    //phone = phone.replace(/(\d{3})(\d{3})/, '$1-$2-');
}
else {
    // whatever you want to tell the user
}

there seems to be a bug in the "replace" regex's above. enter a 10 digit number and you see it formatted correctly (e.g. "(123) 456-7890"). Then, select the contents of the field (double or triple click it) and overtype the value. You'll see the first two digits get transposed. So if you enter 1 2 3, you'll see 2 1 3...

Post a comment

comment list (0)

  1. No comments so far