0% found this document useful (0 votes)
467 views14 pages

JavaScript Regex Guide

This document provides an overview of regular expressions in JavaScript. It describes how to create regular expressions using literals or the RegExp constructor. It also explains how to write regular expression patterns using simple and special characters. Finally, it provides a table defining all the special characters that can be used in regular expression patterns and their meanings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
467 views14 pages

JavaScript Regex Guide

This document provides an overview of regular expressions in JavaScript. It describes how to create regular expressions using literals or the RegExp constructor. It also explains how to write regular expression patterns using simple and special characters. Finally, it provides a table defining all the special characters that can be used in regular expression patterns and their meanings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1/10/2016

RegularExpressionsJavaScript|MDN

[Link]:
[Link]

RegularExpressions
Previous

Next

[Link]
JavaScript,[Link]
andtestmethodsofRegExp,andwiththematch,replace,search,andsplitmethods
[Link].

Creatingaregularexpression
Youconstructaregularexpressioninoneoftwoways:
Usingaregularexpressionliteral,whichconsistsofapatternenclosedbetweenslashes,asfollows:

varre=/ab+c/;

Regularexpressionliteralsprovidecompilationoftheregularexpressionwhenthescriptisloaded.
Whentheregularexpressionwillremainconstant,usethisforbetterperformance.
OrcallingtheconstructorfunctionoftheRegExpobject,asfollows:

varre=newRegExp("ab+c");

[Link]
constructorfunctionwhenyouknowtheregularexpressionpatternwillbechanging,oryoudon'tknow
thepatternandaregettingitfromanothersource,suchasuserinput.

Writingaregularexpressionpattern
Aregularexpressionpatterniscomposedofsimplecharacters,suchas/abc/,oracombinationof
simpleandspecialcharacters,suchas/ab*c/or/Chapter(\d+)\.\d*/.Thelastexampleincludes
[Link]

1/14

1/10/2016

RegularExpressionsJavaScript|MDN

[Link]
rememberedforlateruse,asdescribedinUsingparenthesizedsubstringmatches.

Usingsimplepatterns
[Link],
thepattern/abc/matchescharactercombinationsinstringsonlywhenexactlythecharacters'abc'
[Link]"Hi,doyouknowyour
abc's?"and"Thelatestairplanedesignsevolvedfromslabcraft."Inbothcasesthematchiswiththe
substring'abc'.Thereisnomatchinthestring'Grabcrab'becausewhileitcontainsthesubstring'ab
c',itdoesnotcontaintheexactsubstring'abc'.

Usingspecialcharacters
Whenthesearchforamatchrequiressomethingmorethanadirectmatch,suchasfindingoneor
moreb's,orfindingwhitespace,[Link],thepattern
/ab*c/matchesanycharactercombinationinwhichasingle'a'isfollowedbyzeroormore'b's(*
means0ormoreoccurrencesoftheprecedingitem)andthenimmediatelyfollowedby'c'.Inthestring
"cbbabbbbcdebc,"thepatternmatchesthesubstring'abbbbc'.
Thefollowingtableprovidesacompletelistanddescriptionofthespecialcharactersthatcanbeused
inregularexpressions.
Specialcharactersinregularexpressions.
Character

Meaning
Matchesaccordingtothefollowingrules:
Abackslashthatprecedesanonspecialcharacterindicatesthatthenextcharacteris
[Link],a'b'withoutapreceding'\'
generallymatcheslowercase'b'[Link]'\b'byitselfdoesn't
matchanycharacteritformsthespecialwordboundarycharacter.

Abackslashthatprecedesaspecialcharacterindicatesthatthenextcharacterisnot
[Link],thepattern/a*/reliesonthe
specialcharacter'*'tomatch0ormorea'[Link],thepattern/a\*/removes
thespecialnessofthe'*'toenablematcheswithstringslike'a*'.
Donotforgettoescape\itselfwhileusingtheRegExp("pattern")notationbecause\is
alsoanescapecharacterinstrings.

[Link],alsomatchesimmediately
afteralinebreakcharacter.
^

Forexample,/^A/doesnotmatchthe'A'in"anA",butdoesmatchthe'A'in"AnE".

[Link]

2/14

1/10/2016

RegularExpressionsJavaScript|MDN

The'^'hasadifferentmeaningwhenitappearsasthefirstcharacterinacharacter
[Link].
[Link],alsomatchesimmediately
beforealinebreakcharacter.
$
Forexample,/t$/doesnotmatchthe't'in"eater",butdoesmatchitin"eat".

[Link]{0,}.
*

Forexample,/bo*/matches'boooo'in"Aghostbooooed"and'b'in"Abirdwarbled",
butnothingin"Agoatgrunted".

[Link]{1,}.
+

Forexample,/a+/matchesthe'a'in"candy"andallthea'sin"caaaaaaandy",but
nothingin"cndy".

[Link]{0,1}.
Forexample,/e?le?/matchesthe'el'in"angel"andthe'le'in"angle"andalsothe'l'
in"oslo".

Ifusedimmediatelyafteranyofthequantifiers*,+,?,or{},makesthequantifiernon
greedy(matchingthefewestpossiblecharacters),asopposedtothedefault,whichis
greedy(matchingasmanycharactersaspossible).Forexample,applying/\d+/to
"123abc"matches"123".Butapplying/\d+?/tothatsamestringmatchesonlythe"1".
Alsousedinlookaheadassertions,asdescribedinthex(?=y)andx(?!y)entriesof
thistable.

(Thedecimalpoint)matchesanysinglecharacterexceptthenewlinecharacter.

Forexample,/.n/matches'an'and'on'in"nay,anappleisonthetree",butnot
'nay'.

Matches'x'andremembersthematch,[Link]
parenthesesarecalledcapturingparentheses.

(x)

The'(foo)'and'(bar)'inthepattern/(foo)(bar)\1\2/matchandremember
thefirsttwowordsinthestring"foobarfoobar".The\1and\2inthepatternmatch
thestring'[Link]\1,\2,\nareusedinthematchingpartofthe

[Link]

3/14

1/10/2016

RegularExpressionsJavaScript|MDN

[Link]$1,$2,$nmustbeused,e.g.:
'barfoo'.replace(/(...)(...)/,'$2$1').

Matches'x'[Link]
capturingparentheses,andletyoudefinesubexpressionsforregularexpression
(?:x)

[Link]/(?:foo){1,2}/.Ifthe
expressionwas/foo{1,2}/,the{1,2}characterswouldapplyonlytothelast'o'in
'foo'.Withthenoncapturingparentheses,the{1,2}appliestotheentireword'foo'.
Matches'x'onlyif'x'isfollowedby'y'.Thisiscalledalookahead.

x(?=y)

Forexample,/Jack(?=Sprat)/matches'Jack'onlyifitisfollowedby'Sprat'./Jack(?
=Sprat|Frost)/matches'Jack'onlyifitisfollowedby'Sprat'or'Frost'.However,
neither'Sprat'nor'Frost'ispartofthematchresults.

Matches'x'onlyif'x'isnotfollowedby'y'.Thisiscalledanegatedlookahead.

x(?!y)

Forexample,/\d+(?!\.)/matchesanumberonlyifitisnotfollowedbyadecimal
[Link]/\d+(?!\.)/.exec("3.141")matches'141'butnot
'3.141'.

Matcheseither'x'or'y'.
x|y

Forexample,/green|red/matches'green'in"greenapple"and'red'in"redapple."

[Link]
integer.
{n}
Forexample,/a{2}/doesn'tmatchthe'a'in"candy,"butitdoesmatchallofthea's
in"caandy,"andthefirsttwoa'sin"caaandy."
Wherenandmarepositiveintegersandn<=[Link]
[Link],it'streatedas.
{n,m}

Forexample,/a{1,3}/matchesnothingin"cndy",the'a'in"candy,"thefirsttwoa's
in"caandy,"andthefirstthreea'sin"caaaaaaandy".Noticethatwhenmatching
"caaaaaaandy",thematchis"aaa",eventhoughtheoriginalstringhadmorea'sinit.

[Link],
[Link](.)andasterisk(*)arenot

[xyz]

specialinsideacharacterset,sotheydon'[Link]
rangeofcharactersbyusingahyphen,asthefollowingexamplesillustrate.

[Link]

4/14

1/10/2016

RegularExpressionsJavaScript|MDN

Thepattern[ad],whichperformsthesamematchas[abcd],matchesthe'b'in
"brisket"andthe'c'in"city".Thepatterns/[az.]+/and/[\w.]+/matchtheentire
string"[Link]".
[Link],itmatchesanythingthatisnot
[Link].
Everythingthatworksinthenormalcharactersetalsoworkshere.
[^xyz]
Forexample,[^abc]isthesameas[^ac].Theyinitiallymatch'r'in"brisket"and'h'
in"chop."

[\b]

Matchesabackspace(U+0008).Youneedtousesquarebracketsifyouwantto
matchaliteralbackspacecharacter.(Nottobeconfusedwith\b.)
[Link]
[Link]
[Link],thelengthofa
matchedwordboundaryiszero.(Nottobeconfusedwith[\b].)
Examples:
/\bm/matchesthe'm'in"moon"
/oo\b/doesnotmatchthe'oo'in"moon",because'oo'isfollowedby'n'whichisa
wordcharacter

\b

/oon\b/matchesthe'oon'in"moon",because'oon'istheendofthestring,thusnot
followedbyawordcharacter
/\w\b\w/willnevermatchanything,becauseawordcharactercanneverbefollowed
bybothanonwordandawordcharacter.

Note: JavaScript'sregularexpressionenginedefinesa specificsetofcharacterstobe


"word"[Link]
charactersisfairlylimited:itconsistssolelyoftheRomanalphabetinbothupperandlower
case,decimaldigits,[Link],suchas""or""
are,unfortunately,treatedaswordbreaks.

[Link]
characterareofthesametype:Eitherbothmustbewords,orbothmustbenon
[Link].
\B
Forexample,/\B../matches'oo'in"noonday",and/y\B./matches'ye'in"possibly
yesterday."

[Link].
[Link]

5/14

1/10/2016

\cX

RegularExpressionsJavaScript|MDN

Forexample,/\cM/matchescontrolM(U+000D)inastring.

[Link][09].
\d

Forexample,/\d/or/[09]/matches'2'in"B2isthesuitenumber."

[Link][^09].
\D

Forexample,/\D/or/[^09]/matches'B'in"B2isthesuitenumber."

\f

Matchesaformfeed(U+000C).

\n

Matchesalinefeed(U+000A).

\r

Matchesacarriagereturn(U+000D).
Matchesasinglewhitespacecharacter,includingspace,tab,formfeed,linefeed.
Equivalentto[\f\n\r\t\v\u00a0\u1680\u180e\u2000

\s

\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].
Forexample,/\s\w*/matches'bar'in"foobar."

[Link][^

\S

\f\n\r\t\v\u00a0\u1680\u180e\u2000
\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].
Forexample,/\S\w*/matches'foo'in"foobar."

\t

Matchesatab(U+0009).

\v

Matchesaverticaltab(U+000B).
[Link][AZa
z09_].

\w
Forexample,/\w/matches'a'in"apple,"'5'in"$5.28,"and'3'in"3D."

[Link][^AZaz09_].
\W

Forexample,/\W/or/[^AZaz09_]/matches'%'in"50%."

[Link]

6/14

1/10/2016

RegularExpressionsJavaScript|MDN

Wherenisapositiveinteger,abackreferencetothelastsubstringmatchingthen
parentheticalintheregularexpression(countingleftparentheses).
\n

Forexample,/apple(,)\sorange\1/matches'apple,orange,'in"apple,orange,
cherry,peach."

\0

MatchesaNULL(U+0000)[Link],because
\0<digits>isanoctalescapesequence.

\xhh

Matchesthecharacterwiththecodehh(twohexadecimaldigits)

\uhhhh

Matchesthecharacterwiththecodehhhh(fourhexadecimaldigits).

Escapinguserinputtobetreatedasaliteralstringwithinaregularexpressioncanbeaccomplishedby
simplereplacement:

functionescapeRegExp(string){
[Link](/[.*+?^${}()|[\]\\]/g,"\\$&");

Usingparentheses
Parenthesesaroundanypartoftheregularexpressionpatterncausethatpartofthematched
[Link],thesubstringcanberecalledforotheruse,as
describedinUsingParenthesizedSubstringMatches.
Forexample,thepattern/Chapter(\d+)\.\d*/illustratesadditionalescapedandspecialcharacters
[Link]
'Chapter'followedbyoneormorenumericcharacters(\dmeansanynumericcharacterand+means
1ormoretimes),followedbyadecimalpoint(whichinitselfisaspecialcharacterprecedingthe
decimalpointwith\meansthepatternmustlookfortheliteralcharacter'.'),followedbyanynumeric
character0ormoretimes(\dmeansnumericcharacter,*means0ormoretimes).Inaddition,
parenthesesareusedtorememberthefirstmatchednumericcharacters.
Thispatternisfoundin"OpenChapter4.3,paragraph6"and'4'[Link]
foundin"Chapter3and4",becausethatstringdoesnothaveaperiodafterthe'3'.
Tomatchasubstringwithoutcausingthematchedparttoberemembered,withintheparentheses
prefacethepatternwith?:.Forexample,(?:\d+)matchesoneormorenumericcharactersbutdoes
notrememberthematchedcharacters.

Workingwithregularexpressions
[Link]

7/14

1/10/2016

RegularExpressionsJavaScript|MDN

RegularexpressionsareusedwiththeRegExpmethodstestandexecandwiththeStringmethods
match,replace,search,[Link]
reference.
Methodsthatuseregularexpressions
Method

[Link]

exec

information.

test

[Link].
[Link]

match

informationornullonamismatch.
[Link],or
1ifthesearchfails.

search

replace

split

Description

AStringmethodthatexecutesasearchforamatchinastring,andreplacesthe
matchedsubstringwithareplacementsubstring.
AStringmethodthatusesaregularexpressionorafixedstringtobreakastringinto
anarrayofsubstrings.

Whenyouwanttoknowwhetherapatternisfoundinastring,usethetestorsearchmethodfor
moreinformation(butslowerexecution)[Link]
ifthematchsucceeds,thesemethodsreturnanarrayandupdatepropertiesoftheassociatedregular
expressionobjectandalsoofthepredefinedregularexpressionobject,[Link],the
execmethodreturnsnull(whichcoercestofalse).
Inthefollowingexample,thescriptusestheexecmethodtofindamatchinastring.

varmyRe=/d(b+)d/g;

varmyArray=[Link]("cdbbdbsbz");

Ifyoudonotneedtoaccessthepropertiesoftheregularexpression,analternativewayofcreating
myArrayiswiththisscript:

varmyArray=/d(b+)d/[Link]("cdbbdbsbz");

Ifyouwanttoconstructtheregularexpressionfromastring,yetanotheralternativeisthisscript:

varmyRe=newRegExp("d(b+)d","g");

varmyArray=[Link]("cdbbdbsbz");

[Link]

8/14

1/10/2016

RegularExpressionsJavaScript|MDN

Withthesescripts,thematchsucceedsandreturnsthearrayandupdatesthepropertiesshowninthe
followingtable.
Resultsofregularexpressionexecution.
Property

Object

orindex

myArray

Description

Inthis
example
["dbbd",

Thematchedstringandallrememberedsubstrings.

index

The0basedindexofthematchintheinputstring.

input

Theoriginalstring.

"cdbbdbsbz"

[0]

Thelastmatchedcharacters.

"dbbd"

"bb"]

Theindexatwhichtostartthenextmatch.(Thisproperty
lastIndex
myRe
source

issetonlyiftheregularexpressionusesthegoption,
describedinAdvancedSearchingWithFlags.)
[Link]
regularexpressioniscreated,notexecuted.

"d(b+)d"

Asshowninthesecondformofthisexample,youcanusearegularexpressioncreatedwithanobject
[Link],however,everyoccurrenceisanewregular
[Link],ifyouusethisformwithoutassigningittoavariable,youcannot
[Link],assumeyouhavethis
script:

1
2

varmyRe=/d(b+)d/g;
varmyArray=[Link]("cdbbdbsbz");

3
4

[Link]("ThevalueoflastIndexis"+[Link]);

//"ThevalueoflastIndexis5"

However,ifyouhavethisscript:

1
2

varmyArray=/d(b+)d/[Link]("cdbbdbsbz");
[Link]("ThevalueoflastIndexis"+/d(b+)d/[Link]);

3
4

//"ThevalueoflastIndexis0"

Theoccurrencesof/d(b+)d/ginthetwostatementsaredifferentregularexpressionobjectsand
[Link]

9/14

1/10/2016

RegularExpressionsJavaScript|MDN

[Link]
regularexpressioncreatedwithanobjectinitializer,youshouldfirstassignittoavariable.

Usingparenthesizedsubstringmatches
Includingparenthesesinaregularexpressionpatterncausesthecorrespondingsubmatchtobe
[Link],/a(b)c/matchesthecharacters'abc'andremembers'b'.Torecallthese
parenthesizedsubstringmatches,usetheArrayelements[1],...,[n].
[Link]
[Link].
Thefollowingscriptusesthereplace()[Link]
text,thescriptusesthe$1and$2inthereplacementtodenotethefirstandsecondparenthesized
substringmatches.

varre=/(\w+)\s(\w+)/;
varstr="JohnSmith";

varnewstr=[Link](re,"$2,$1");

[Link](newstr);

Thisprints"Smith,John".

Advancedsearchingwithflags
Regularexpressionshavefouroptionalflagsthatallowforglobalandcaseinsensitivesearching.
Theseflagscanbeusedseparatelyortogetherinanyorder,andareincludedaspartoftheregular
expression.
Regularexpressionflags
Flag

Description

Globalsearch.

Caseinsensitivesearch.

Multilinesearch.
Performa"sticky"searchthatmatchesstartingatthecurrentpositioninthetargetstring.

Seesticky

Toincludeaflagwiththeregularexpression,usethissyntax:

varre=/pattern/flags;

[Link]

10/14

1/10/2016

RegularExpressionsJavaScript|MDN

or

varre=newRegExp("pattern","flags");

[Link]
later.
Forexample,re=/\w+\s/gcreatesaregularexpressionthatlooksforoneormorecharacters
followedbyaspace,anditlooksforthiscombinationthroughoutthestring.

1
2
3
4

varre=/\w+\s/g;
varstr="feefifofum";
varmyArray=[Link](re);
[Link](myArray);

Thisdisplays["fee","fi","fo"].Inthisexample,youcouldreplacetheline:

varre=/\w+\s/g;

with:

varre=newRegExp("\\w+\\s","g");

andgetthesameresult.
[Link]
isused,^and$matchatthestartorendofanylinewithintheinputstringinsteadofthestartorend
oftheentirestring.

Examples
Thefollowingexamplesshowsomeusesofregularexpressions.

Changingtheorderinaninputstring
[Link]()
[Link]().Itcleansaroughlyformattedinputstringcontainingnames(firstnamefirst)
separatedbyblanks,[Link],itreversesthenameorder(lastname
first)andsortsthelist.

[Link]

11/14

1/10/2016

RegularExpressionsJavaScript|MDN

//Thenamestringcontainsmultiplespacesandtabs,

2
3

//andmayhavemultiplespacesbetweenfirstandlastnames.
varnames="HarryTrump;FredBarney;HelenRigby;BillAbel;ChrisHand";

4
5

varoutput=["OriginalString\n",names+"\n"];

6
7

//Preparetworegularexpressionpatternsandarraystorage.

//Splitthestringintoarrayelements.

9
10

//pattern:possiblewhitespacethensemicolonthenpossiblewhitespace

11
12

varpattern=/\s*;\s*/;

13
14

//Breakthestringintopiecesseparatedbythepatternaboveand
//storethepiecesinanarraycallednameList

15

varnameList=[Link](pattern);

16
17

//newpattern:oneormorecharactersthenspacesthencharacters.

18

//Useparenthesesto"memorize"portionsofthepattern.

19
20

//Thememorizedportionsarereferredtolater.
pattern=/(\w+)\s+(\w+)/;

21
22

//Newarrayforholdingnamesbeingprocessed.

23

varbySurnameList=[];

24
25

//Displaythenamearrayandpopulatethenewarray

26

//withcommaseparatednames,lastfirst.

27

//

28
29

//Thereplacemethodremovesanythingmatchingthepattern

30
31

//followedbycommaspacefollowedbyfirstmemorizedportion.
//

32

//Thevariables$1and$2refertotheportions

33

//memorizedwhilematchingthepattern.

//andreplacesitwiththememorizedstringsecondmemorizedportion

34
35

[Link]("AfterSplitbyRegularExpression");

36
37
38

vari,len;

39

for(i=0,len=[Link];i<len;i++){
[Link](nameList[i]);

40

bySurnameList[i]=nameList[i].replace(pattern,"$2,$1");

41

42
43

//Displaythenewarray.

44

[Link]("NamesReversed");

45
46

for(i=0,len=[Link];i<len;i++){
[Link](bySurnameList[i]);

[Link]

12/14

1/10/2016

47

RegularExpressionsJavaScript|MDN

48
49

//Sortbylastname,thendisplaythesortedarray.

50

[Link]();

51

[Link]("Sorted");

52

for(i=0,len=[Link];i<len;i++){

53

[Link](bySurnameList[i]);

54

55
56

[Link]("End");

57
58

[Link]([Link]("\n"));

Usingspecialcharacterstoverifyinput
Inthefollowingexample,[Link]
"Check"button,[Link](matchesthe
charactersequencespecifiedbytheregularexpression),thescriptshowsamessagethankingthe
[Link],thescriptinformstheuserthatthephone
numberisnotvalid.
Withinnoncapturingparentheses(?:,theregularexpressionlooksforthreenumericcharacters
\d{3}OR|aleftparenthesis\(followedbythreedigits\d{3},followedbyacloseparenthesis\),
(endnoncapturingparenthesis)),followedbyonedash,forwardslash,ordecimalpointandwhen
found,rememberthecharacter([\/\.]),followedbythreedigits\d{3},followedbythe
rememberedmatchofadash,forwardslash,ordecimalpoint\1,followedbyfourdigits\d{4}.
[Link].

<!DOCTYPEhtml>

<html>

<head>

<metahttpequiv="ContentType"content="text/html;charset=ISO88591">

<metahttpequiv="ContentScriptType"content="text/javascript">

6
7

<scripttype="text/javascript">

functiontestInfo(phoneInput){
varOK=[Link]([Link]);

varre=/(?:\d{3}|\(\d{3}\))([\/\.])\d{3}\1\d{4}/;

10

if(!OK)

11

[Link]([Link]+"isn'taphonenumberwithareacode!"

12

else

13

[Link]("Thanks,yourphonenumberis"+OK[0]);

14

15

</script>

[Link]

13/14

1/10/2016

RegularExpressionsJavaScript|MDN

16

</head>

17
18

<body>
<p>Enteryourphonenumber(withareacode)andthenclick"Check".

19

<br>Theexpectedformatislike##########.</p>

20

<formaction="#">

21

<inputid="phone"><buttononclick="testInfo([Link]('phone

22

</form>

23

</body>

24

</html>

Previous

Next

Share: Twitter Facebook Google+

[Link]

14/14

You might also like