JavaScript:Regular Expressions

From virtualMV2015wiki
Jump to: navigation, search
 Home  JavaScript <


Regular Expressions are a good way of validating text fields. Basically, you create a string of characters that represents a validation and test it against a string. This approach compacts a lot of potentially confusing validation code down into a few lines.


In order to use a Regular Expression in JavaScript, you need to create a regex literal variable. So something like:

var myRegex = /^[a-z\s]+$/i;

The above says "do a case-insensitive check for alphabetical characters and spaces only".

/ - Start of a JavaScript regular expression
^ - Match the first character with the following
[a-z - Match the letters a through to z
\s] - Match spaces
+ - Use the previous rule for every character in the string
$ - Match the last character
/i - End of a JavaScript regular expression, and also sets the mode to case-insensitive

(Andersson, 2008)[1] gives an explanation of other patterns)

To test it against a string, we can use the "test" method that becomes available every time we create a variable containing a regular expression literal.

var rexLowerAlpha = /^[a-z\s]+$/i;
var strFail = "This test should fail!!!1111";
if (rexLowerAlpha.test(strFail)) {
  //do this if the test succeeds
} else {
  //do this if the test fails

The above is just for a match case, search and replace can also be done using regexs, as well as splitting strings up into arrays etc.

Alternatively you can create a string and then create a new regular expression object, for example:

    var rexStr1 = "^[a-z\s]+$/i;";
    var rexLowerAlpha = new RegExp(rexStr1);

Example jsRegExp_01.htm

There are heaps of pre-created regular expressions available here:

  • (2009)[2]

Useful patterns

Regular expressionWhat it does
/^[A-Z\s]+$/;Check for Uppercase A-Z plus space
/^[0-9]+$/;Check for integer e.g. 123,
/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;matches a date in yyyy-mm-dd format from between 1900-01-01 and 2099-12-31, with a choice of four separators (-,/,space, and .) [3]


Icon References.png References

  1. Andersson, D. (2008) Regular Expressions patterns. Retrieved June 8, 2009 from
  2. (2009) Regular Expression Library. Retrieved May 13, 2009 from
  3. Regular Expression Matching a Valid Date. Retrieved May 26, 2011 from
  4. (Chodnicki, S.(2011). An Introduction to Regular Expressions. Retrieved from
  5. RegExLibrary (2011) Dates and Times. Retrieved May 26, 2011 from

JavaScript:Regular Expressions. (2017). In virtualMV's ( Michael Verhaart ) wiki. Retrieved December 13, 2017, from    (zotero)
  • Contributors
    • ErinD Apr 2009