Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 23, 2022 04:17 am

JavaScript Regex Cheat Sheet


Successfully working with regular expressions requires you to know what each special character, flag and method does. This is a regular expressions cheat sheet which you can refer to when trying to remember how a method, special character or flag works.


Creating a Regular Expression in JavaScript

























MethodExampleBenefits 
Regular Expression Literal/^(\d+)/better performance 
Constructor Functionnew RegExp('^(\d+)')can use variables 

Matching a Specific Set of Characters

















































OperatorMatchesOperatorMatches
.any character  
[abc]any character listed[^abc]any character not listed
\wword characters\Wnon-word characters
\ddigits\Dnon-digits
\swhitespace\Snon-whitespace
\bword boundaries\Bnon-word boundaries

Specifying the Number of Times to Match



































SymbolMeaningSymbolMeaning
^beginning of the line or string$end of the line or string
*zero or more repetitions+one or more repetitions
?possibly exists
{n}specific number of repetitions{n,m}range of repetitions

Using Flags With Regular Expressions

























FlagMeaningFlagMeaning
gglobalmmultiline mode
icase-insensitiveysticky search

Parenthesis in Regular Expressions


Regular Expression Methods in JavaScript































FunctionPurpose
test()test if a pattern matches
search()find a matching pattern
match() and exec()get matches
replace()replace matched text
split()split on matches


Creating a Regular Expression in JavaScript


There are two ways of defining a regular expression in JavaScript.



Regular Expression Literal


var rgx = /^(\d+)/ — You can use a regular expression literal and enclose the pattern between slashes. This is evaluated at compile time and provides better performance if the regular expression stays constant.



Constructor Function


var rgx = new RegExp('^(\d+)') — The constructor function is useful when the regular expression may change programmatically. These are compiled during runtime.


[back]



Matching a Specific Set of Characters


The following sequences can be used to match a specific set of characters.



Any Character .


The period matches any character except the newline '\n'.






























ExpressionStringResult
..ano matches
 ab1 match: ab
 abc1 match: ab
 abcde2 matches: ab and cd


Custom Character Groups [...]


The square brackets are used to specify a collection of characters. [abc] would match the letter a, b or c. [a-z] would match any letter between a and z


With a ^ symbol, the square brackets match any character not listed. For example [^0-9] matches any non digit character.



































ExpressionStringResult
[abc]amatch: a
[abc]acmatches: a and c
[abc]Hello!no matches
[abc]The boy is happy.matches: b and a
[^0-9]user1234matches: u, s, e, and r


Word Characters \w and \W


\w matches word characters. Word characters are alphanumeric (a-z, A-Z characters, and underscore).\W Matches non-word characters. Everything except alphanumeric characters and underscore.






























ExpressionStringResult
\w12"&; :c3 matches: 1, 2 and c
\w%>"!no matches
\W12"&; :c4 matches: ", &, : and ;
\Wtutorialno matches


Digit Characters \d and \D


\d matches digit characters. Any digit from 0 to 9. Equivalent to [0-9] in bracket notation.\D matches non-digit characters. Everything except 0 to 9. Equivalent to [^0-9] in bracket notation.






























ExpressionStringResult
\d\d\d123tea41 match: 123
\dtutorialno match
\D12tea3"44 matches: t, e, a ,and "
\D123no match


Whitespace Characters \s and \S


\s matches whitespace characters. This includes spaces, tabs, and line breaks. Whitespace is equivalent to [\t\n\r\f\v] with bracket notation.\S  matches all other characters except whitespace. Equivalent to [^ \t\n\r\f\v].

























ExpressionStringResult
\sa b c2 matches
\stutorialno match
\Sa b c3 matches: a, b, and c


Beginning or End of Word \b or Not \B


\b matches the beginning or end of a word.






























ExpressionStringResult
\bcupa cupboardmatch: cup
cup\bthe cupboardno match
cup\bthe teacup is yellowmatch: cup
\bcupenglishcupofteano match

\B matches only within a word.

























ExpressionStringResult
\Bcupcupboardno match
cup\Bcupboardmatch: cup
cup\Bteacupno match


Caret ^


The caret symbol ^ matches the beginning of the string.






























ExpressionStringResult
^abano match
^ababmatch: ab
^ababcmatch: ab
^abacb

no match




Dollar $


The dollar symbol $ matches the end of the string.

























ExpressionStringResult
ab$ano match
ab$abmatch: ab
ab$abcno match

[back]



Specifying the Number of Times to Match


All the meta-characters given below can be used to evaluate patterns based on the number of times a character is repeated. You can add quantifiers to specify how many characters should be included in the match at once.



Star *


The * symbol is used to check if there are zero, or more occurrences of the pattern to the left of the symbol.






























ExpressionStringResult
ab*cacmatch: ac
ab*cabbcmatch: abbc
ab*cadno match
ab*cabd

no match 




Plus +


The + symbol is used to check if there is at least occurrence of the pattern to the left of the symbol.

























ExpressionStringResult
ab+cacno match
ab+cabcmatch: abc
ab+cdabbcd

match: abbc




Question ?


The ? symbol is used to check if there is zero or one occurrence of the pattern to the left of the symbol.

























ExpressionStringResult
ab?cacmatch: ac
ab+cabbcno match
ab+cabc

match: abc




Number of Repetitions {n} or {n,m}


Braces with a single number denote a specific number of repetitions. If the brace has two numbers, in the format {n,m}, n denotes the minimum, and m denotes the maximum number of repetitions of the pattern to the left.



































ExpressionStringResult
a{2,3}abc defno match
a{2,3}abc daad1 match: aa
a{2,3}aabc daaad2 matches: aa and aaa
[0-9]{2,4}4no match
[0-9]{2,4}12 here 345678 there

3 matches: 12, 3456, and 78



[back]



Using Flags with Regular Expressions


Flags can be used to control how a regular expression should be interpreted. You can use flags either alone or together in any order you want. these are the five flags which are available in JavaScript. 



Global g


g—search the string for all matches of given expression instead of returning just the first one.



Case-Insensitive i


i— make the search case-insensitive so that words like apple, Apple and APPLE can all be matched at once.



Multiline Mode m


m—make the ^ and $ tokens look for a match at the beginning or end of each line instead of the whole string.


Unicode Mode u


u— enable Unicode code point escapes in your regular expression. Not all browsers support this option. 




Sticky Search y


y—only look for a match at the current position in the target string. lastindex indicates where the search will begin.


[back]



Parenthesis in Regular Expressions


The parenthesis is used for grouping. Sub patterns can be formed using ().

























ExpressionStringResult
(ab)+abmatch: ab
 ababcdmatch: abab
 cabaacdmatch: ab

You can also combine the or | operator with () to combine pick from a number of possible patterns.

























ExpressionStringResult
([0-9]|[x])+a123x3bmatch: 123x3
 axdmatch: x
 c9x23d3matches: 9x23 and 3

Finally, the parts of a matching string that match some pattern in brackets will be broken out and returned separately. This means you can use regular expressions to extract or modify data from a string. 


It's with nested patterns that the power of regular expressions really starts to become apparent.


[back]



Regular Expression Methods in JavaScript


The regular expressions that you create using the flags and character sequences we have discussed so far are meant to be used with JavaScript methods to search, replace or split a string. Here are some methods related to regular expressions.



Test if A Pattern Matches test()


test()—check if the main string contains a substring which matches the pattern specified by the given regular expression. It returns true on a successful match and false otherwise.


search()—check if the main string contains a substring which matches the pattern specified by the given regular expression. It returns the index of the match on success and -1 otherwise.




Get Matches match() and exec()


match()—search if the main string contains a substring which matches the pattern specified by the given regular expression. If the g flag is enabled, multiple matches will be returned as an array.



exec()—search if the main string contains a substring which matches the pattern specified by the given regular expression. The returned array will contain information about the match and capturing groups.




Replace Matched Text replace()


replace()— search for a substring matching the given pattern and replace it with the provided replacement string.




Split on Matches split()


split()— this method will allow you to split the main string into substrings based on the separator specified as a regular expression.



[back]



Conclusion


In previous tutorials, we have covered the basics of regular expressions as well as some more complicated expressions which can prove to be useful every once in a while. These two tutorials explained how different characters or character sequences work in regular expressions.



Original Link: https://code.tutsplus.com/tutorials/a-simple-regex-cheat-sheet--cms-31278

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code