- Javascript Regex Cheat Sheet 2019
- Regex Builder
- Javascript Regex Cheat Sheet Free
- Javascript Regex Cheat Sheet
JavaScript RegExp Defination
The JavaScript RegExp object explains the patterns of characters. These patterns are used in search, validation, and search and replace functionality in JS programming.
JavaScript RegExp Syntax
In above example the /infopediya/i
is example of JS RegExp.
The /infopediya/
is a pattern and /i
is a modifier. we will explain the modifiers in JavaScript RegExp Syntax Cheat Sheet.
REGEX CHEAT SHEET The most commonly used metacharacters in Python, PHP, Perl, JavaScript, and Ruby regular expressions Metacharacters Meaning n Newline Range or character class ^ Not in range or negated character class. (dot or point) Any character except newline w Word character a-zA-Z0-9 W Nonword character ^a-zA-Z0-9. JavaScript PCRE Python JavaScript Regex Cheatsheet. Regular Expression Basics. Any character except newline: a: The character a: ab: The string ab. Regular Expression Special Characters n: Newline r: Carriage return t: Tab 0: Null character YYY: Octal character YYY xYY: Hexadecimal character YY uYYYY: Hexadecimal character YYYY.
- Regular expression syntax cheatsheet This page provides an overall cheat sheet of all the capabilities of RegExp syntax by aggregating the content of the articles in the RegExp guide. If you need more information on a specific topic, please follow the link on the corresponding heading to access the full article or head to the guide.
- JavaScript Regex Cheat Sheet. By Monty Shokeen 21 Jun 2018. Length: Medium Languages: Regular Expressions JavaScript Language Fundamentals Programming Fundamentals. Indonesian (Bahasa Indonesia) translation by Lukman Nulhakim (you can also view the original English.
- Test your regex by visualizing it with a live editor. JavaScript, Python, and PCRE.
How to create a pattern using a constructor?
It is easy to create a pattern using the new RegExp()
. It creates a new RegExp object.
Here the pattern variable will give you the ” /Hello World/g ” as output. The new RegExp accepts two parameters the string and modifier.
In the above example ‘ Hello World ‘ is the string pattern and ‘g’ is a modifier given as the parameters to new RegExp()
.
What are modifiers in regular expressions?
The modifiers add a particular behavior/functionality to the whole pattern.
For example, if we want to search a case-insensitive piece of text in a paragraph then the Case Insensitive flag comes in handy. The symbol for Case Insensitive is ” /i “.
The /hello world/i will match ” Hello World ” as well.
Examples
JavaScript RegExp /g Modifier
JavaScript RegExp /i Modifier
JavaScript RegExp /m Modifier
Note: The/m flage is case sensitive. Use it with /gi to search globally with case insesitive matches.
What are JavaScript Regular Expression Quantifiers?
Quantifiers simply show the quantity. consider the following example.
the @ symbol repeats atleat one time and underscore ( _ ) repeats one or more times.
The @ symbol is required but ( _ ) is optional.
Now how to set validation rules for such conditions? The Quantifiers resolve this problem.
JavaScript RegExp [abc] Expression
This expression is used to find any characters given inside the brackets.
You can specify simple characters as [abcd]
.
you can specify any range as from zero to nine [0-9]
. Or from uppercase A to lowercase z[A-z]
.
JavaScript RegExp [^abc] Expression
This expression is used to find any characters accept given inside the brackets.
This is opposite to [abc]
Expression.
JavaScript RegExp . Metacharacter
The dot metacharacter is very powerful. it is used to match:
1: Every single character
2:A single character
consider the following example
List of JavaScript RegExp Metacharacters
Download JavaScript RegExp Syntax Cheat Sheet, the PDF File Here.
References
Above diagram created using Regulex
This blog post gives an overview of regular expression syntax and features supported by JavaScript. Examples have been tested on Chrome/Chromium console (version 81+) and includes features not available in other browsers and platforms. Assume ASCII character set unless otherwise specified. This post is an excerpt from my JavaScript RegExp book.
Elements that define a regular expression🔗
Note | Description |
---|---|
MDN: Regular Expressions | MDN documentation for JavaScript regular expressions |
/pat/ | a RegExp object |
const pet = /dog/ | save regexp in a variable for reuse, clarity, etc |
/pat/.test(s) | Check if given pattern is present anywhere in input string |
returns true or false | |
i | flag to ignore case when matching alphabets |
g | flag to match all occurrences |
new RegExp('pat', 'i') | construct RegExp from a string |
second argument specifies flags | |
use backtick strings with ${} for interpolation | |
source | property to convert RegExp object to string |
helps to insert a RegExp inside another RegExp | |
flags | property to get flags of a RegExp object |
s.replace(/pat/, 'repl') | method for search and replace |
s.search(/pat/) | gives starting location of the match or -1 |
s.split(/pat/) | split a string based on regexp |
Anchors | Description |
---|---|
^ | restricts the match to start of string |
$ | restricts the match to end of string |
m | flag to match the start/end of line with ^ and $ anchors |
r , n , u2028 and u2029 are line separators | |
dos-style files use rn , may need special attention | |
b | restricts the match to start/end of words |
word characters: alphabets, digits, underscore | |
B | matches wherever b doesn't match |
^
, $
and are metacharacters in the above table, as these characters have special meaning. Prefix a
character to remove the special meaning and match such characters literally. For example,
^
will match a ^
character instead of acting as an anchor.
Feature | Description |
---|---|
pat1|pat2|pat3 | multiple regexp combined as OR conditional |
each alternative can have independent anchors | |
(pat) | group pattern(s), also a capturing group |
a(b|c)d | same as abd|acd |
(?:pat) | non-capturing group |
(?<name>pat) | named capture group |
. | match any character except line separators |
[] | Character class, matches one character among many |
Greedy Quantifiers | Description |
---|---|
? | match 0 or 1 times |
* | match 0 or more times |
+ | match 1 or more times |
{m,n} | match m to n times |
{m,} | match at least m times |
{n} | match exactly n times |
pat1.*pat2 | any number of characters between pat1 and pat2 |
pat1.*pat2|pat2.*pat1 | match both pat1 and pat2 in any order |
Greedy here means that the above quantifiers will match as much as possible that'll also honor the overall regexp. Appending a ?
to greedy quantifiers makes them non-greedy, i.e. match as minimally as possible. Quantifiers can be applied to literal characters, groups, backreferences and character classes.
Character class | Description |
---|---|
[ae;o] | match any of these characters once |
[3-7] | range of characters from 3 to 7 |
[^=b2] | negated set, match other than = or b or 2 |
[a-z-] | - should be first/last or escaped using to match literally |
[+^] | ^ shouldn't be first character or escaped using
|
[]] | ] and should be escaped using
|
w | similar to [A-Za-z0-9_] for matching word characters |
d | similar to [0-9] for matching digit characters |
s | similar to [ tnrfv] for matching whitespace characters |
use W , D , and S for their opposites respectively | |
u | flag to enable unicode matching |
p{} | Unicode character sets |
P{} | negated unicode character sets |
see MDN: Unicode property escapes for details | |
u{} | specify unicode characters using codepoints |
Javascript Regex Cheat Sheet 2019
Lookarounds | Description |
---|---|
lookarounds | allows to create custom positive/negative assertions |
zero-width like anchors and not part of matching portions | |
(?!pat) | negative lookahead assertion |
(?<!pat) | negative lookbehind assertion |
(?=pat) | positive lookahead assertion |
(?<=pat) | positive lookbehind assertion |
variable length lookbehind is allowed | |
(?!pat1)(?=pat2) | multiple assertions can be specified next to each other in any order |
as they mark a matching location without consuming characters | |
((?!pat).)* | Negates a regexp pattern |
Matched portion | Description |
---|---|
m = s.match(/pat/) | assuming g flag isn't used and regexp succeeds, |
returns an array with matched portion and 3 properties | |
index property gives the starting location of the match | |
input property gives the input string s | |
groups property gives dictionary of named capture groups | |
m[0] | for above case, gives entire matched portion |
m[N] | matched portion of Nth capture group |
s.match(/pat/g) | returns only the matched portions, no properties |
s.matchAll(/pat/g) | returns an iterator containing details for |
each matched portion and its properties | |
Backreference | gives matched portion of Nth capture group |
use $1 , $2 , $3 , etc in replacement section | |
$& gives entire matched portion | |
$` gives string before the matched portion | |
$' gives string after the matched portion | |
use 1 , 2 , 3 , etc within regexp definition | |
$$ | insert $ literally in replacement section |
$0N | same as $N , allows to separate backreference and other digits |
Nxhh | allows to separate backreference and digits in regexp definition |
(?<name>pat) | named capture group |
use k<name> for backreferencing in regexp definition | |
use $<name> for backreferencing in replacement section |
Regular expression examples🔗
test
method
new RegExp()
constructor
- string and line anchors
replace
method and word boundaries
- alternations and grouping
- MDN: Regular Expressions doc provides
escapeRegExp
function, useful to automatically escape metacharacters.- See also XRegExp utility which provides XRegExp.escape and XRegExp.union methods. The union method has additional functionality of allowing a mix of string and RegExp literals and also takes care of renumbering backreferences.
- dot metacharacter and quantifiers
match
method
matchAll
method
- function/dictionary in replacement section
split
method
Regex Builder
- backreferencing with normal/non-capturing/named capture groups
- examples for lookarounds
Debugging and Visualization tools🔗
As your regexp gets complicated, it can get difficult to debug if you run into issues. Building your regexp step by step from scratch and testing against input strings will go a long way in correcting the problem. To aid in such a process, you could use various online regexp tools.
Javascript Regex Cheat Sheet Free
regex101 is a popular site to test your regexp. You'll have first choose the flavor as JavaScript. Then you can add your regexp, input strings, choose flags and an optional replacement string. Matching portions will be highlighted and explanation is offered in separate panes. There's also a quick reference and other features like sharing, code generator, quiz, etc.
Another useful tool is jex: regulex which converts your regexp to a rail road diagram, thus providing a visual aid to understanding the pattern.
JavaScript RegExp book🔗
Javascript Regex Cheat Sheet
Visit my repo learn_js_regexp for details about the book I wrote on JavaScript regular expressions. The ebook uses plenty of examples to explain the concepts from the basics and includes exercises to test your understanding. The cheatsheet and examples presented in this post are based on contents of this book.