views:

69

answers:

1

Is there a way I can format for example: 0000000000 into (000)000-0000? I'm returning a listbox which holds a collection of phone number which arent formated yet. What I would like is format it. This is what I have in the View:

<%= Html.ListBox("phoneList")%>

and from the controller:

ViewData["phoneList"] = new SelectList(phoneList);

Edit

$('#phoneList').each(function() {
                var phoneNumber = $(this).text();
                var formatPhoneNumber = phoneNumber.replace(/(\d{3})(\d{3})(\d{4})/, '($1)$2-$3');
                alert(formatPhoneNumber);
            });

how would I assign this back to show in the ListBox?

+3  A: 

If you're saying that you want to do it on the client side, then given the phone number in a variable, you could do this:

http://jsfiddle.net/HZbXv/

var str = "0000000000";

var res = '(' + str.substr(0,3) + ')' + str.substr(3,3) + '-' + str.substr(6);

alert(res);

or this:

http://jsfiddle.net/HZbXv/1/

var str = "0000000000";

var res = str.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3');

alert(res);

EDIT:

As noted by @Nick Craver The second version can be shortened up with:

var res = str.replace(/(\d{3})(\d{3})(\d{4})/, '($1)$2-$3');
patrick dw
+1 - Just a note you can slim it down a bit further: `str.replace(/(\d{3})(\d{3})(\d{4})/, '($1)$2-$3');`
Nick Craver
@Nick - Good point. I tend to forget about quantifiers.
patrick dw
@ Nick and patrick -- thanks guys!
hersh