Wednesday, April 03, 2013

Basic Regular Expression Patterns III

1. Problem : Trim a string i.e remove multiple whitespaces from both end of the string.
    Answer :
   var patt = /^\s+|\s+$/
 var str  = "   (This needs to be trimmed)     ";
 str = str.replace(patt, "");
 console.log(str); //(This needs to be trimmed)

  
   Explanation :
   a. ^\s+ means one or more whitespaces at the beginning of the string
   b. | means OR
   c. \s+$ means one or more whitespaces at the end of the string
   So, the whole pattern tries to match with one or more whitespaces at the beginning of the string OR one or more whitespaces at the end of the string and REPLACES them with "" [The second parameter of the function replace()].

2. Problem : Remove all digits from a given string
    Answer :
   var str = "AVF67H90-TGSE23JU-O7T6E32";
  var patt = /[0-9]/;
  str = str.replace( patt, "" );
  console.log(str); //AVF67H90-TGSE23JU-O7T6E32


   Explanation : The problem with the above REGEXP Pattern is that is only replaces the first occurrence of any digit from the string. As a result, the fouth character '6' is replaced from the whole string. We just need to change the pattern as shown below.
   

 var patt = /[0-9]/g;  
// We added a global modifier by mentioning 'g'

 By using modifier 'g', we mean that all occurrences of the matching pattern should be changed/replaced.
 The answer is : AVFH-TGSEJU-OTE

3. Problem : Remove all non-digits from a given number
     Answer :
  var str = "#$%AV^^&?.>-=+_)(*&F67H90-TG{}\'|}{~!@#$%SE23JU-O7T6E32";
  var patt = /[^\d]/g;
  str = str.replace( patt, "" );
  console.log(str); //6790237632


   Explanation :
   a. \d means all digits
   b. [^\d] means capture all those single character which is not a digit. "^" inside [] means we don't want to capture the specified character(s)
   c. /g means global replacements


Check out the (xxx)xxx-xxx formatted phone number validation in Javascript.

Check out the next part of this article here.

No comments: