1

I have a line of code on the server that I want to move to the client page in javascript.

string ThePhone = "1234567890";
string ThisFormat = Regex.Replace(ThePhone, @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");

It's supposed to return 123-456-7890. How can I change this to javascript?

Thanks.

2
  • @Marcus: tried several trial-and-error changes. Can you help? Commented Jan 5, 2012 at 21:04
  • Kobi's answer should work. Here's an example were the given example works: jsfiddle.net/BBTfN Commented Jan 5, 2012 at 21:10

1 Answer 1

2

It is almost exactly the same in this case:

phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');

Notes:

  • You need the /g flag (/.../g) if the string may contain more than one phone (but then we may also want \b)
  • \d in .Net matches all Unicode digits, in JavaScript it only matches [0-9].
Sign up to request clarification or add additional context in comments.

4 Comments

In addition, there are other ways to achieve that - you can insert dashes at the right positions, or you replace /(\d{3})(\d{3})/ with '$1-$2-'.
It doesn't seem to work; I know it's close but I've struggling with this conversion too. It only contains one phone; it's a string of 10 digits. When I alert the result, I get the same initial string.
@frenchie - Works for me: jsbin.com/esoyat . Did you forget the phone = part by any chance?
Ok, I got it: a bit earlier in the code, I was looping through the phone number and doing a parseInt on each character to see if it was an int. When it got to the 0, it dropped that character so I was actually passing 123456789 instead of the 10 digits. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.