Академический Документы
Профессиональный Документы
Культура Документы
2015
JavaScriptRegularExpressionsSimpleUsage
Home
ComputerMain
Products
Tutorials
CompletelyFree
MailingList
RegularExpressionSimpleUsage
Regularexpressionsaren'treallythatdifficult,eventhoughtheywouldn'twinanybeautycontests.Weallknow
someofthem,suchasthe"*"andthe"?"whichareusedinwindow'ssearches.
ThispagewaswrittenoriginallyforthephptutorialandhasbeenmodifiedforJavaScript.
WhenusingtheseinJavaScript,theregularexpressionisenclosedinforwardslashes,andthewholeisenclosed
inquotes.
UsethispagetotryoutregularexpressionsinJavaScript.Itisprobablybettertoexperimentwithyourown
regularexpressionsthanonlytoreadaboutthem.TryouttheexamplesonthispageintheRegularExpression
Checker.
Onthispage:
1. Usage
a.
i. match
ii. replace
iii. search
b. Flags(i,g,m)
c. Period,Asterisk,PlusandQuestionMark
i. ThePeriod
ii. TheAsterisk(*)
iii. ThePlus(+)
iv. TheQuestionMark(?)
d. TheBeginning(^)andtheEnd($),andtheCharacterClass([])
i. CharacterClass([])
ii. Selectingstringsbeginningwith...
iii. Selectingstringsendingwith...
iv. Selectingstringsbeginningwith...andendingwith...
i. SpecialcharactersbecomenormalcharactersinaCharacterClass
e. Matchingagivennumberoftimes{2}
f. Sayingwhatyoudon'twant[^...
g. ThePipes,orgivingachoiceofmatch
h. EmailChecker
Usage
Notearegularexpression,suchas/o/isNOTastring(soitisneverenclosedinquotes).Whenaregular
expressionisenteredbyauserinaform,weneedtochangetheformvaluefromastring.Forexample
str="hellofolks"
re="/o/"//thisisastring,soitwon'twork
re=eval(re)//changeittoanobject
check=str.replace(re,"a")
alert(check)
match
str="hellofolks"
re=/o/
check=str.match(re)
alert(check)
//resultis"o"
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
1/4
8.6.2015
JavaScriptRegularExpressionsSimpleUsage
//otherwiseitreturnsnull
replace
str="hellofolks"
re=/o/
check=str.replace(re,"a")
alert(check)
//resultis"hellafolks"
search
searchcanbeusedtofindthepositionofthefirstoccurrenceofamatch:
str="hellofolks"
re="/o/"
re=eval(re)
check=str.search(re)
document.write(check)
//resultis4
Flags (i, g, m)
Theiflagmakesthesearchcaseinsensitive.Thegmakesthesearchglobal,findingallmatchesandnotjustthe
first.Andthemflagcoversmultiplelines.
/rea/matchesbread
/rea/imatchesbReAd
/rea/gmatchesbreadbREAdbread
/rea/gimatchesbreadbREAdbread
matchthe"b"inbread,becausethereisnocharacterbeforethe"b"inbread.Theremustbeoneor
morecharactersinthe"."space.
"breadreadtedbaa".match(/b*d/)matches"e"inbread.Itdoesn'tcareaboutthe"b"becauseitmatcheszero
ormoreofthepreceding.
/cat*/gmatchesallthecatsin"catcatamarancaterconcatenate".
Oftenwemustescapetheasteriskinjavascriptbecause/*lookslikeacommenttojavascript.Weneed,therefore
towrite/\\*/
Thequestionmarkwilloftenbeescapedtoo.
2/4
8.6.2015
JavaScriptRegularExpressionsSimpleUsage
re=/c(at)*/g
reis:/c(at)*/g
str.match(/c(at)*/g)gives:"c,c,c,cat,catatat"
However,theplusgivesus:
str='caatctccatcatatat'
re=/c(at)+/g
reis:/c(at)+/g
str.match(/c(at)+/g)gives:"cat,catatat"
str.search(/c(at)+/g)givestheindexofthefirstoccurence:11
Thatis,theremustbeatleastoneprecedingitemtogiveamatch.Notethebrackets(at)beforetheplusmeans
thatthewholeofthecontentsofthebracketareconsidered.Inthiscase,theymustoccuratleastoncefora
match.
The Beginning (^) and the End ($), and the Character Class
([])
Character Class ([])
Well,let'sstartattheendwiththeCharacterClass.Forinstance,/[09]/selectsallthenumbercharacters,and
/[aeiou]/selectsallthelowercasevowels./[az]/selectsallthelowercaseletters,and/[AZ]/selectsallthe
uppercaseletters.
3/4
8.6.2015
JavaScriptRegularExpressionsSimpleUsage
Email Checker
Thefollowingisanexampleofanemailchecker.Therearemanysuchregularexpressions,andnoneofthem
workwithallemailaddresses.
/^[azAZ09][azAZ09_\s]+@[azAZ09\s].+\.[azAZ]{2,5}$/
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
4/4