Vous êtes sur la page 1sur 14

1/10/2016

RegularExpressionsJavaScript|MDN

Wewanttohelpdeveloperslikeyou.Tellushowyouusedeveloperservices:
https://qsurvey.mozilla.com/s3/da2a7841fe76

RegularExpressions
Previous

Next

Regularexpressionsarepatternsusedtomatchcharactercombinationsinstrings.In
JavaScript,regularexpressionsarealsoobjects.Thesepatternsareusedwiththeexec
andtestmethodsofRegExp,andwiththematch,replace,search,andsplitmethods
ofString.ThischapterdescribesJavaScriptregularexpressions.

Creatingaregularexpression
Youconstructaregularexpressioninoneoftwoways:
Usingaregularexpressionliteral,whichconsistsofapatternenclosedbetweenslashes,asfollows:

varre=/ab+c/;

Regularexpressionliteralsprovidecompilationoftheregularexpressionwhenthescriptisloaded.
Whentheregularexpressionwillremainconstant,usethisforbetterperformance.
OrcallingtheconstructorfunctionoftheRegExpobject,asfollows:

varre=newRegExp("ab+c");

Usingtheconstructorfunctionprovidesruntimecompilationoftheregularexpression.Usethe
constructorfunctionwhenyouknowtheregularexpressionpatternwillbechanging,oryoudon'tknow
thepatternandaregettingitfromanothersource,suchasuserinput.

Writingaregularexpressionpattern
Aregularexpressionpatterniscomposedofsimplecharacters,suchas/abc/,oracombinationof
simpleandspecialcharacters,suchas/ab*c/or/Chapter(\d+)\.\d*/.Thelastexampleincludes
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

1/14

1/10/2016

RegularExpressionsJavaScript|MDN

parentheseswhichareusedasamemorydevice.Thematchmadewiththispartofthepatternis
rememberedforlateruse,asdescribedinUsingparenthesizedsubstringmatches.

Usingsimplepatterns
Simplepatternsareconstructedofcharactersforwhichyouwanttofindadirectmatch.Forexample,
thepattern/abc/matchescharactercombinationsinstringsonlywhenexactlythecharacters'abc'
occurtogetherandinthatorder.Suchamatchwouldsucceedinthestrings"Hi,doyouknowyour
abc's?"and"Thelatestairplanedesignsevolvedfromslabcraft."Inbothcasesthematchiswiththe
substring'abc'.Thereisnomatchinthestring'Grabcrab'becausewhileitcontainsthesubstring'ab
c',itdoesnotcontaintheexactsubstring'abc'.

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

Meaning
Matchesaccordingtothefollowingrules:
Abackslashthatprecedesanonspecialcharacterindicatesthatthenextcharacteris
specialandisnottobeinterpretedliterally.Forexample,a'b'withoutapreceding'\'
generallymatcheslowercase'b'swherevertheyoccur.Buta'\b'byitselfdoesn't
matchanycharacteritformsthespecialwordboundarycharacter.

Abackslashthatprecedesaspecialcharacterindicatesthatthenextcharacterisnot
specialandshouldbeinterpretedliterally.Forexample,thepattern/a*/reliesonthe
specialcharacter'*'tomatch0ormorea's.Bycontrast,thepattern/a\*/removes
thespecialnessofthe'*'toenablematcheswithstringslike'a*'.
Donotforgettoescape\itselfwhileusingtheRegExp("pattern")notationbecause\is
alsoanescapecharacterinstrings.

Matchesbeginningofinput.Ifthemultilineflagissettotrue,alsomatchesimmediately
afteralinebreakcharacter.
^

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

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

2/14

1/10/2016

RegularExpressionsJavaScript|MDN

The'^'hasadifferentmeaningwhenitappearsasthefirstcharacterinacharacter
setpattern.Seecomplementedcharactersetsfordetailsandanexample.
Matchesendofinput.Ifthemultilineflagissettotrue,alsomatchesimmediately
beforealinebreakcharacter.
$
Forexample,/t$/doesnotmatchthe't'in"eater",butdoesmatchitin"eat".

Matchestheprecedingexpression0ormoretimes.Equivalentto{0,}.
*

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

Matchestheprecedingexpression1ormoretimes.Equivalentto{1,}.
+

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

Matchestheprecedingexpression0or1time.Equivalentto{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,asthefollowingexampleshows.The
parenthesesarecalledcapturingparentheses.

(x)

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

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

3/14

1/10/2016

RegularExpressionsJavaScript|MDN

regex.Inthereplacementpartofaregexthesyntax$1,$2,$nmustbeused,e.g.:
'barfoo'.replace(/(...)(...)/,'$2$1').

Matches'x'butdoesnotrememberthematch.Theparenthesesarecallednon
capturingparentheses,andletyoudefinesubexpressionsforregularexpression
(?:x)

operatorstoworkwith.Considerthesampleexpression/(?: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
point.Theregularexpression/\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."

Matchesexactlynoccurrencesoftheprecedingexpression.Nmustbeapositive
integer.
{n}
Forexample,/a{2}/doesn'tmatchthe'a'in"candy,"butitdoesmatchallofthea's
in"caandy,"andthefirsttwoa'sin"caaandy."
Wherenandmarepositiveintegersandn<=m.Matchesatleastnandatmostm
occurrencesoftheprecedingexpression.Whenmisomitted,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.

Characterset.Thispatterntypematchesanyoneofthecharactersinthebrackets,
includingescapesequences.Specialcharacterslikethedot(.)andasterisk(*)arenot

[xyz]

specialinsideacharacterset,sotheydon'tneedtobeescaped.Youcanspecifya
rangeofcharactersbyusingahyphen,asthefollowingexamplesillustrate.

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

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"test.i.ng".
Anegatedorcomplementedcharacterset.Thatis,itmatchesanythingthatisnot
enclosedinthebrackets.Youcanspecifyarangeofcharactersbyusingahyphen.
Everythingthatworksinthenormalcharactersetalsoworkshere.
[^xyz]
Forexample,[^abc]isthesameas[^ac].Theyinitiallymatch'r'in"brisket"and'h'
in"chop."

[\b]

Matchesabackspace(U+0008).Youneedtousesquarebracketsifyouwantto
matchaliteralbackspacecharacter.(Nottobeconfusedwith\b.)
Matchesawordboundary.Awordboundarymatchesthepositionwhereaword
characterisnotfollowedorpreceededbyanotherwordcharacter.Notethata
matchedwordboundaryisnotincludedinthematch.Inotherwords,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"characters.Anycharacternotinthatsetisconsideredawordbreak.Thissetof
charactersisfairlylimited:itconsistssolelyoftheRomanalphabetinbothupperandlower
case,decimaldigits,andtheunderscorecharacter.Accentedcharacters,suchas""or""
are,unfortunately,treatedaswordbreaks.

Matchesanonwordboundary.Thismatchesapositionwherethepreviousandnext
characterareofthesametype:Eitherbothmustbewords,orbothmustbenon
words.Thebeginningandendofastringareconsiderednonwords.
\B
Forexample,/\B../matches'oo'in"noonday",and/y\B./matches'ye'in"possibly
yesterday."

WhereXisacharacterrangingfromAtoZ.Matchesacontrolcharacterinastring.
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

5/14

1/10/2016

\cX

RegularExpressionsJavaScript|MDN

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

Matchesadigitcharacter.Equivalentto[09].
\d

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

Matchesanynondigitcharacter.Equivalentto[^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."

Matchesasinglecharacterotherthanwhitespace.Equivalentto[^

\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).
Matchesanyalphanumericcharacterincludingtheunderscore.Equivalentto[AZa
z09_].

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

Matchesanynonwordcharacter.Equivalentto[^AZaz09_].
\W

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

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

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)character.Donotfollowthiswithanotherdigit,because
\0<digits>isanoctalescapesequence.

\xhh

Matchesthecharacterwiththecodehh(twohexadecimaldigits)

\uhhhh

Matchesthecharacterwiththecodehhhh(fourhexadecimaldigits).

Escapinguserinputtobetreatedasaliteralstringwithinaregularexpressioncanbeaccomplishedby
simplereplacement:

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

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

Workingwithregularexpressions
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

7/14

1/10/2016

RegularExpressionsJavaScript|MDN

RegularexpressionsareusedwiththeRegExpmethodstestandexecandwiththeStringmethods
match,replace,search,andsplit.ThesemethodsareexplainedindetailintheJavaScript
reference.
Methodsthatuseregularexpressions
Method

ARegExpmethodthatexecutesasearchforamatchinastring.Itreturnsanarrayof

exec

information.

test

ARegExpmethodthattestsforamatchinastring.Itreturnstrueorfalse.
AStringmethodthatexecutesasearchforamatchinastring.Itreturnsanarrayof

match

informationornullonamismatch.
AStringmethodthattestsforamatchinastring.Itreturnstheindexofthematch,or
1ifthesearchfails.

search

replace

split

Description

AStringmethodthatexecutesasearchforamatchinastring,andreplacesthe
matchedsubstringwithareplacementsubstring.
AStringmethodthatusesaregularexpressionorafixedstringtobreakastringinto
anarrayofsubstrings.

Whenyouwanttoknowwhetherapatternisfoundinastring,usethetestorsearchmethodfor
moreinformation(butslowerexecution)usetheexecormatchmethods.Ifyouuseexecormatchand
ifthematchsucceeds,thesemethodsreturnanarrayandupdatepropertiesoftheassociatedregular
expressionobjectandalsoofthepredefinedregularexpressionobject,RegExp.Ifthematchfails,the
execmethodreturnsnull(whichcoercestofalse).
Inthefollowingexample,thescriptusestheexecmethodtofindamatchinastring.

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

varmyArray=myRe.exec("cdbbdbsbz");

Ifyoudonotneedtoaccessthepropertiesoftheregularexpression,analternativewayofcreating
myArrayiswiththisscript:

varmyArray=/d(b+)d/g.exec("cdbbdbsbz");

Ifyouwanttoconstructtheregularexpressionfromastring,yetanotheralternativeisthisscript:

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

varmyArray=myRe.exec("cdbbdbsbz");

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

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.)
Thetextofthepattern.Updatedatthetimethatthe
regularexpressioniscreated,notexecuted.

"d(b+)d"

Asshowninthesecondformofthisexample,youcanusearegularexpressioncreatedwithanobject
initializerwithoutassigningittoavariable.Ifyoudo,however,everyoccurrenceisanewregular
expression.Forthisreason,ifyouusethisformwithoutassigningittoavariable,youcannot
subsequentlyaccessthepropertiesofthatregularexpression.Forexample,assumeyouhavethis
script:

1
2

varmyRe=/d(b+)d/g;
varmyArray=myRe.exec("cdbbdbsbz");

3
4

console.log("ThevalueoflastIndexis"+myRe.lastIndex);

//"ThevalueoflastIndexis5"

However,ifyouhavethisscript:

1
2

varmyArray=/d(b+)d/g.exec("cdbbdbsbz");
console.log("ThevalueoflastIndexis"+/d(b+)d/g.lastIndex);

3
4

//"ThevalueoflastIndexis0"

Theoccurrencesof/d(b+)d/ginthetwostatementsaredifferentregularexpressionobjectsand
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

9/14

1/10/2016

RegularExpressionsJavaScript|MDN

hencehavedifferentvaluesfortheirlastIndexproperty.Ifyouneedtoaccessthepropertiesofa
regularexpressioncreatedwithanobjectinitializer,youshouldfirstassignittoavariable.

Usingparenthesizedsubstringmatches
Includingparenthesesinaregularexpressionpatterncausesthecorrespondingsubmatchtobe
remembered.Forexample,/a(b)c/matchesthecharacters'abc'andremembers'b'.Torecallthese
parenthesizedsubstringmatches,usetheArrayelements[1],...,[n].
Thenumberofpossibleparenthesizedsubstringsisunlimited.Thereturnedarrayholdsallthatwere
found.Thefollowingexamplesillustratehowtouseparenthesizedsubstringmatches.
Thefollowingscriptusesthereplace()methodtoswitchthewordsinthestring.Forthereplacement
text,thescriptusesthe$1and$2inthereplacementtodenotethefirstandsecondparenthesized
substringmatches.

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

varnewstr=str.replace(re,"$2,$1");

console.log(newstr);

Thisprints"Smith,John".

Advancedsearchingwithflags
Regularexpressionshavefouroptionalflagsthatallowforglobalandcaseinsensitivesearching.
Theseflagscanbeusedseparatelyortogetherinanyorder,andareincludedaspartoftheregular
expression.
Regularexpressionflags
Flag

Description

Globalsearch.

Caseinsensitivesearch.

Multilinesearch.
Performa"sticky"searchthatmatchesstartingatthecurrentpositioninthetargetstring.

Seesticky

Toincludeaflagwiththeregularexpression,usethissyntax:

varre=/pattern/flags;

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

10/14

1/10/2016

RegularExpressionsJavaScript|MDN

or

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

Notethattheflagsareanintegralpartofaregularexpression.Theycannotbeaddedorremoved
later.
Forexample,re=/\w+\s/gcreatesaregularexpressionthatlooksforoneormorecharacters
followedbyaspace,anditlooksforthiscombinationthroughoutthestring.

1
2
3
4

varre=/\w+\s/g;
varstr="feefifofum";
varmyArray=str.match(re);
console.log(myArray);

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

varre=/\w+\s/g;

with:

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

andgetthesameresult.
Themflagisusedtospecifythatamultilineinputstringshouldbetreatedasmultiplelines.Ifthemflag
isused,^and$matchatthestartorendofanylinewithintheinputstringinsteadofthestartorend
oftheentirestring.

Examples
Thefollowingexamplesshowsomeusesofregularexpressions.

Changingtheorderinaninputstring
Thefollowingexampleillustratestheformationofregularexpressionsandtheuseofstring.split()
andstring.replace().Itcleansaroughlyformattedinputstringcontainingnames(firstnamefirst)
separatedbyblanks,tabsandexactlyonesemicolon.Finally,itreversesthenameorder(lastname
first)andsortsthelist.

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

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=names.split(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

output.push("AfterSplitbyRegularExpression");

36
37
38

vari,len;

39

for(i=0,len=nameList.length;i<len;i++){
output.push(nameList[i]);

40

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

41

42
43

//Displaythenewarray.

44

output.push("NamesReversed");

45
46

for(i=0,len=bySurnameList.length;i<len;i++){
output.push(bySurnameList[i]);

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

12/14

1/10/2016

47

RegularExpressionsJavaScript|MDN

48
49

//Sortbylastname,thendisplaythesortedarray.

50

bySurnameList.sort();

51

output.push("Sorted");

52

for(i=0,len=bySurnameList.length;i<len;i++){

53

output.push(bySurnameList[i]);

54

55
56

output.push("End");

57
58

console.log(output.join("\n"));

Usingspecialcharacterstoverifyinput
Inthefollowingexample,theuserisexpectedtoenteraphonenumber.Whentheuserpressesthe
"Check"button,thescriptchecksthevalidityofthenumber.Ifthenumberisvalid(matchesthe
charactersequencespecifiedbytheregularexpression),thescriptshowsamessagethankingthe
userandconfirmingthenumber.Ifthenumberisinvalid,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}.
TheChangeeventactivatedwhentheuserpressesEntersetsthevalueofRegExp.input.

<!DOCTYPEhtml>

<html>

<head>

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

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

6
7

<scripttype="text/javascript">

functiontestInfo(phoneInput){
varOK=re.exec(phoneInput.value);

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

10

if(!OK)

11

window.alert(phoneInput.value+"isn'taphonenumberwithareacode!"

12

else

13

window.alert("Thanks,yourphonenumberis"+OK[0]);

14

15

</script>

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

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(document.getElementById('phone

22

</form>

23

</body>

24

</html>

Previous

Next

Share: Twitter Facebook Google+

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

14/14

Vous aimerez peut-être aussi