2

I a trying to come with a regex to create a standard UK mobile number. From what I have seen in the data set, the numbers come in the following different formats

+44 (0) 7111111111
+44 71111111111
44 71111111111
07111111111
NULL

What I am looking to do is have all of them start with 07, followed by 9 numbers e.g.

07111111111

So the first thing I need to do is remove all spaces

var origmob = "+44 (0) 1111111111";
newmOB = origmob.replace(/\s/g, "");
console.log(newmOB);

Next, I need to somehow match

+44(0)
OR
+44
OR
44
OR
0 //This one is correct, not sure if I need to check this

This is where I think I become a bit stuck. At the moment I have this

var origmob = "+44 (0) 1111111111";
newmOB = origmob.replace(/ /g, "").replace(/^(\+44\(0\)|(\+44)|(44))/g, "0");
console.log(newmOB);

It kind of works sometimes, but I do not think it is very good. It does not start the string with 07, and it does not check the length after this. It also does not replace NULL with an empty string.

How could I improve this mixture of regex and replace to format different numbers into the standard format I am after?

Thanks

1
  • Personally, I wouldn't try to smush everything into one regular expression. Those things get unwieldy very quickly. At the very least, I'd make the NULL check a separate case. Commented Feb 10, 2016 at 20:01

4 Answers 4

2

You'd better check for NULL in a separate - and pretty direct - replace. For all the other cases, here's one possible approach:

/(\+?\s*44\s*(?:\(?0\)?)?\s*)(?=7\d{9})/

Demo. Matched is the replaced part:

  • optional +
  • any number of whitespace
  • 44
  • any number of whitespace
  • optional group: (?0)? (? means the character is optional in this group)
  • again, any number of whitespace
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply get the last 9 numbers and append it to 07:

newmOB = origmob.replace(/.*(\d{9})$/g, "07$1");

In case of NULL, it can be done with a separate condition.

See the example.

1 Comment

Thanks, never thought of this :-) I marked this as correct because I think it is the best approach. Thanks
1

You can use:

var str = '+44 (0) 7111111111';
var repl = '0' + str.replace(/\D+/g, '').slice(-10);
//=> "07111111111"

So what we are doing is this:

  1. Start with a literal 0
  2. Remove all non-digits from input
  3. Take last 10 digits from replaced text

Comments

1

Regex:

^.*(\d{9})$

This matches from string start anything up to the 9 digits, then the 9 digits then string end.

Substitute with:

07\1

This will give you 07 then the 9 digits that were matched in the regex.

Demo: https://regex101.com/r/sB8oM3/1

Comments

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.