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 sensitiveg
– finds all matches not just first matchm
– multiline matching
RegExp Methods
exec()
– returns first match if foundtest()
– 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
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 characterw
– character in wordW
– non-word characterd
– digitD
– not a digitn
– newline characters
– white spaceS
– not white spaceb
– Find a match at the beginning/end of a wordB
– 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 xx?
– string has zero or more occurrences of xx{y}
– string has a y number of x's in sequencex{y,z}
– string has a minimum of y x's and maximum of z x's in sequencex{y,}
– string has a minimum of y x's in sequencex$
– string ends with x^x
– string begins with x?=x
– string is followed by string x?!x
– string is not followed by string x