Pattern matching in jQuery?
I have strings(phone numbers) like this:
1112223333
1234567890
And I want to convert these lik开发者_Python百科e this:
(111)222-3333
(123)456-7890
How to do this is jQuery.
Thanks
var phone = '1234567890';
phone.replace(/^(\d{3})(\d{3})(\d+)$/, '($1)$2-$3'); // (123)456-7890
See it on jsFiddle.
If you want to match that length exactly, use a {4}
quantifier in place of the last +
.
No jquery needed, just javascript regular expressions:
var aNumber = '1112223333';
var aPhoneNumber = aNumber.replace(/^(\d{3})(\d{3})(\d{4})$/, '($1)$2-$3');
By the way, I'm assuming numbers are always of the form '(xxx)xxx-xxxx', 3-3-4 numbers.
精彩评论