10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency

globe-Vista-256x256In a previous post trim a string from white space by JavaScript function ( or Another JavaScript function for trim a string from white space ) and JavaScript function-Splits the string by given separator and returns an array with trimmed items, Some Regular expressions have been used. Regular expressions are very powerful tools for performing pattern matches.And validating user input is the bane of every software developer existence. But these patterns used in RegExp can be very simple.


Fortunately, JavaScript 1.2+ has incorporated regular expressions.JavaScript has an alternate syntax for creating Regular Expression objects that implicitly calls the RegExp constructor function.A regular expression pattern is composed of simple characters, such as /abc/, the syntax for that method is the following:

var RegularExpression = /pattern/[switch]

To use the Regular Expression object to validate the user input you must be able to define a pattern string that represents the search criteria. Patterns are defined using string literal characters and metacharacters. The following is some useful regular expression based javascript function, some works like validating user input will be very simple by using them. :)

No.1: Check if string is non-blank

// Check if string is non-blank
var isNonblank_re    = /\S/;
function isNonblank (s) {
   return String (s).search (isNonblank_re) != -1
}

No.2: Check if string is a whole number(digits only).

// Check if string is a whole number(digits only).
var isWhole_re       = /^\s*\d+\s*$/;
function isWhole (s) {
   return String(s).search (isWhole_re) != -1
}

or as seen in the following snippet:

// check 0-9 digit
function regIsDigit(fData)
{
    var reg = new RegExp(”^[0-9]$”);
    return (reg.test(fData));
}

No.3: Checks that an input string is an integer

// checks that an input string is an integer, with an optional +/- sign character.
var isInteger_re     = /^\s*(\+|-)?\d+\s*$/;
function isInteger (s) {
   return String(s).search (isInteger_re) != -1
}

or as seen in the following snippet:

// check is number
function regIsNumber(fData)
{
    var reg = new RegExp(”^[-]?[0-9]+[\.]?[0-9]+$”);
    return reg.test(fData)
}

No.4: Checks that an input string is a decimal number

// Checks that an input string is a decimal number, with an optional +/- sign character.
var isDecimal_re     = /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;
function isDecimal (s) {
   return String(s).search (isDecimal_re) != -1
}

No.5: Check if string is currency
works just like isDecimal, except that only zero or two digits are allowed after the decimal point.

// Check if string is currency
var isCurrency_re    = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
   return String(s).search (isCurrency_re) != -1
}

No.6: Checks that an input string looks like a valid email address

// checks that an input string looks like a valid email address.
var isEmail_re       = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail (s) {
   return String(s).search (isEmail_re) != -1;
}

or as seen in the following snippet:

// Check if string is a valid email address
function regIsEmail(fData)
  {
      var reg = new RegExp(”^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$”);
      return reg.test(fData);
  }

No.7: Check for valid credit card type/number

// Check for valid credit card type/number
var creditCardList = [
   //type      prefix   length
   ["amex",    "34",    15],
   ["amex",    "37",    15],
   ["disc",    "6011",  16],
   ["mc",      "51",    16],
   ["mc",      "52",    16],
   ["mc",      "53",    16],
   ["mc",      "54",    16],
   ["mc",      "55",    16],
   ["visa",    "4",     13],
   ["visa",    "4",     16]
];
function isValidCC (cctype, ccnumber) {
   var cc = getdigits (ccnumber);
   if (luhn (cc)) {
      for (var i in creditCardList) {
         if (creditCardList [i][0] == (cctype.toLowerCase ())) {
            if (cc.indexOf (creditCardList [i][1]) == 0) {
               if (creditCardList [i][2] == cc.length) {
                  return true;
               }
            }
         }
      }
   }
   return false;
}

or as seen in the following snippet:

This is the luhn checksum algorithm, used to validate such things as credit card numbers and bank routing numbers.

function luhn (cc) {
   var sum = 0;
   var i;

   for (i = cc.length - 2; i >= 0; i -= 2) {
      sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
   }
   for (i = cc.length - 1; i >= 0; i -= 2) {
      sum += parseInt (cc.charAt (i), 10);
   }
   return (sum % 10) == 0;
}

No.8: Returns a string with everything but the digits removed

// This returns a string with everything but the digits removed.
function getdigits (s) {
   return s.replace (/[^\d]/g, “”);
}

No.9: Get String Length
// Get String Length

// Get String Length
function regGetStrLength(fData)
{
    var valLength = fData.length;
    var reg = new RegExp(”^[\u0391-\uFFE5]$”);
    var result = 0;
    for(i=0; i< valLength; i++)
    {
        if(reg.test(fData.charAt(i)))
        {
            result += 2;
        }
        else
        {
            result ++;
        }
    }
    return result;
}

No.10: Trim a string from white space
Trim a string from white space
@see previous post trim a string from white space by JavaScript function pls. :)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

23 Responses to “10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency”

  1. Marc says:

    I am a bit puzzled as to why there are samples in there for functions which are already available in JavaScript:

    Get String Length:
    “string”.length

    Figuring out if something is a number:
    isNaN(’1a23′)

    parseInt or parseFloat ring a bell?

  2. [...] 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency – Ntt… – [...]

  3. maht says:

    Great goodness. gracias.

  4. sukdev garai says:

    It is very helpful

  5. hongwei says:

    for check email one, it is not correct, if like dan_ney@hotmail.com, it is correct email address, but the expression will not accept it.

  6. ur says:

    there is a problem in no 8
    1. // This returns a string with everything but the digits removed.
    2. function getdigits (s) {
    3. return s.replace (/[^\d]/g, “”);
    4. }

    sometimes I want to have the number 2.5(decimal). can u make a function that clear anything but digets but leave decimak number?
    4.5.5->4.55
    4.5a->4.5

  7. Luke says:

    hey ur,

    Here is modified verion of no. 8 that will handle decimals:

    function getDecimal(str) {
    return str.match(/.*\.|.*/)[0].replace(/[^\d]/g, “”) + str.match(/(?:\.[\d]*)?$/)[0];
    }

  8. Luke says:

    Already found a bug, try this:

    function getDecimal(str) {
    return str.match(/.*\.|.*/)[0].replace(/[^\d]/g, “”) + str.match(/(?:\..*)?$/)[0].replace(/[^0-9\.]/g, “”);
    }

  9. Luke says:

    One last iteration, the factional part selector was to aggressive.

    function getDecimal(str) {
    return str.match(/.*\.|.*/)[0].replace(/[^\d]/g, “”) + str.match(/(?:\.[^\.]*)?$/)[0].replace(/[^0-9\.]/g, “”);
    }

  10. [...] Bookmarked a link on Delicious. 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency – Ntt… [...]

  11. Nitin Sawant says:

    Gr8!! I want to give billion thanx to you….

  12. [...] Valid credit card number (JavaScript, via ntt.cc) [...]

  13. George says:

    thanks! thanks! thanks!

  14. [...] Valid credit card number (JavaScript, via ntt.cc) [...]

  15. anon says:

    This is complete crap.
    Return the length of a string?
    2 seperate email validators both of which fail?
    Did you know that javascript already parses ints and floats.
    Using these functions would actually be less secure

  16. [...] number and decided to do a quick RegExp for validating a USA postal code with JavaScript(@see 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency), in fact, Regular Expressions are included in most of the popular develop languages like PHP, [...]

  17. [...] Valid credit card number (JavaScript, via ntt.cc) [...]

  18. [...] 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency [...]

  19. Akif Patel says:

    Many Many thnx for all the above reg exp.

    But, I found a bug in isDecimal() function.

    Try this: isDecimal(.256), here 0 before decimar is missing.

  20. … and by valid I mean services like Gmail strip out the dots in the username of an email address allowing users to accept email with any number of dots in the name. So, a.b.c @ gmail.com and ab.c @ gmail.com would both end up at abc @ gmail.com

  21. sneha says:

    it waznt helpful at all!!!!!!!!!!!!!!!!!!!!!!!!

  22. Shani says:

    I need a function which checks the format xxx/xxxxxxxxxx

    where x can be alphanemric or digit

    3 characters/digits followed by a forward slash(/) and then 10 digits/characters

Leave a Reply