Home /JavaScript/Regular Expressions

Regex - Regular Expressions

JavaScript RegExp (Regular Expressions) will save your life when you are searching and/or replacing a set characters in a string. It is fundamental for any form validation. RegExp is actually an object. Regular Expressions are common in any language to sift through string values. Usually, RegExp is used to find something inside a string as in some form of validation.

Think about how complex a string truly is. There are so many different characters, combinations and permutations of those characters. What if you wanted to validate that a string contained "I'm awesome", but the case didn't really matter and you wanted to know how many times it was used. JavaScript does have a few methods that might help you with this, but eventually the situation might become too difficult for these. We will need to bring in the powerful RegExp to help us out.

Regular expressions are a very advanced topic. It is all right if you don't completely understand them now, but a reference list of JavaScript's regular expressions will be very beneficial to you in the future.

Modifiers

  • i – not case sensitive
  • g – finds all matches not just first match
  • m – multiline matching

RegExp Methods

  • exec() – returns first match if found
  • test() – returns true if found, false it is isn't found

Example

var example1 = "Meerkats";
var rEPattern1 = /s/gi; // the "s" is what we are searching for
var rEPattern2 = /z/gi; // the "z" is what we are searching for

document.write(rEPattern1.exec(example1) + "<br/>"); // s is found, returns s
document.write(rEPattern2.test(example1) + "<br/>"); // z is not found, returns false

Results

s
false

Brackets

  • [ghi] – returns all characters within the brackets
  • [^ghi] – returns all characters that are not within the brackets
  • [0-9] – returns any digit between 0 and 9
  • [a-z] – returns all lowercase characters between a and z
  • [A-Z] – returns all uppercase characters between A and Z
  • [a-zA-Z] – returns all characters between a and z regardless of case
  • (meerkat|squirrel) – returns any of the alternatives

Metacharacters

  • . – single character
  • w – character in word
  • W – non-word character
  • d – digit
  • D – not a digit
  • n – newline character
  • s – white space
  • S – not white space
  • b – Find a match at the beginning/end of a word
  • B – Find a match not at the beginning/end of a word

Quantifiers

The "x" in the following list can be replaced by anything, including characters, words, numbers, etc.

  • x+ – string has at least one x
  • x? – string has zero or more occurrences of x
  • x{y} – string has a y number of x's in sequence
  • x{y,z} – string has a minimum of y x's and maximum of z x's in sequence
  • x{y,} – string has a minimum of y x's in sequence
  • x$ – string ends with x
  • ^x – string begins with x
  • ?=x – string is followed by string x
  • ?!x – string is not followed by string x