Take few business cards or perhaps advertisements and see how they have shown the phone number. Here are some variants.
A proper phone number has 10 digits; and the first digit must not be a zero.
Let’s get our hands dirty, we know that the phone number can have ONLY numbers. So the first step is to remove all non digit items. Once we do that we take the last 10 digits. Now all we need to do is to check the first digit for zero. Here’s the simplified logic diagram.
A regular expression (RegEx) is really just a sequence or pattern of characters that is matched against a string of text when performing searches and replacements. A simple regular expression consists of a character or set of characters that matches itself. The regular expression is normally delimited by forward slashes; for example, /abc/.
I decided to use the power of the string object with RegEx. The replace() method from the string object is used to search for a string and replace the string with another string. First we need to create the pattern to match. So the line
var regex1 = /[^0-9]/ig; //remove non-digits
Creates a variable named ‘regex1’. [^0–9], matches a non-digit (same as \D), ‘^’ means, negate, ie: NOT in set. The ‘I’ modifier is used to turn off case sensitivity and the ‘g’ modifier makes the replacement global; that is, all occurrences of the found pattern are replaced with the new string.
var phonein = phonein.replace(regex1, "");
Executes the replace method of the string object. What we are saying is to look for the pattern from regex1 and replace them with nothing, or essentially remove them!
Now we need to get the last 10 digits. In order to do that, first we need to find the length of the string. We do this in two steps:
var startpos = phonein.length-10; //find the length phonein = phonein.substr(startpos); //get the last 10 digits
You can test the code here.