RegExp.prototype.test() - JavaScript - MDN Web Docs
文章推薦指數: 80 %
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false . SkiptomaincontentSkiptosearchSkiptoselectlanguageReferencesJavaScriptJavaScriptStandardbuilt-inobjectsRegExpRegExp.prototype.test()ArticleActionsEnglish(US)TryitSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopicsStandardbuilt-inobjectsRegExpPropertiesgetRegExp[@@species]RegExp.prototype.dotAllRegExp.prototype.flagsRegExp.prototype.globalRegExp.prototype.hasIndicesRegExp.prototype.ignoreCase Non-Standard RegExp.input($_)RegExp:lastIndex Non-Standard RegExp.lastMatch($&) Non-Standard RegExp.lastParen($+) Non-Standard RegExp.leftContext($`)RegExp.prototype.multiline Non-Standard RegExp.$1-$9 Non-Standard RegExp.rightContext($')RegExp.prototype.sourceRegExp.prototype.stickyRegExp.prototype.unicodeMethodsRegExp.prototype[@@match]()RegExp.prototype[@@matchAll]()RegExp.prototype[@@replace]()RegExp.prototype[@@search]()RegExp.prototype[@@split]() Deprecated RegExp.prototype.compile()RegExp.prototype.exec()RegExp.prototype.test()RegExp.prototype.toString()Inheritance:FunctionProperties Deprecated Function.arguments Deprecated Function.caller Non-Standard Function.displayNameFunction.lengthFunction.nameMethodsFunction.prototype.apply()Function.prototype.bind()Function.prototype.call()Function.prototype.toString()ObjectPropertiesObject.prototype.constructor Deprecated Object.prototype.__proto__Methods Deprecated Object.prototype.__defineGetter__() Deprecated Object.prototype.__defineSetter__() Deprecated Object.prototype.__lookupGetter__() Deprecated Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.setPrototypeOf()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()TryitSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoRegExp.prototype.test() Thetest()methodexecutesasearchforamatchbetweena regularexpressionandaspecifiedstring.Returnstrueor false. JavaScriptRegExpobjectsarestatefulwhentheyhave theglobalorstickyflags set(e.g.,/foo/gor/foo/y).Theystorea lastIndexfromthepreviousmatch.Usingthis internally,test()canbeusedtoiterateovermultiplematchesinastring oftext(withcapturegroups). TryitSyntaxtest(str) Parameters str Thestringagainstwhichtomatchtheregularexpression. Returns trueifthereisamatchbetweentheregularexpressionandthestring str.Otherwise,false. Description Usetest()wheneveryouwanttoknowwhetherapatternisfoundina string.test()returnsaboolean,unlikethe String.prototype.search()method(whichreturnstheindexofamatch,or -1ifnotfound). Togetmoreinformation(butwithslowerexecution),usethe exec()method.(Thisissimilartothe String.prototype.match()method.) Aswithexec()(orincombinationwithit),test()called multipletimesonthesameglobalregularexpressioninstancewilladvancepastthe previousmatch. ExamplesUsingtest() Simpleexamplethattestsif"hello"iscontainedattheverybeginningof astring,returningabooleanresult. conststr='helloworld!'; constresult=/^hello/.test(str); console.log(result);//true Thefollowingexamplelogsamessagewhichdependsonthesuccessofthetest: functiontestInput(re,str){ letmidstring; if(re.test(str)){ midstring='contains'; }else{ midstring='doesnotcontain'; } console.log(`${str}${midstring}${re.source}`); } Usingtest()onaregexwiththe"global"flag Whenaregexhastheglobalflagset, test()willadvancethelastIndexoftheregex. (RegExp.prototype.exec()alsoadvancesthelastIndexproperty.) Furthercallstotest(str)willresumesearching strstartingfromlastIndex.The lastIndexpropertywillcontinuetoincreaseeachtimetest() returnstrue. Note:Aslongastest()returnstrue, lastIndexwillnotreset—evenwhentestingadifferentstring! Whentest()returnsfalse,thecallingregex's lastIndexpropertywillresetto0. Thefollowingexampledemonstratesthisbehavior: constregex=/foo/g;//the"global"flagisset //regex.lastIndexisat0 regex.test('foo')//true //regex.lastIndexisnowat3 regex.test('foo')//false //regex.lastIndexisat0 regex.test('barfoo')//true //regex.lastIndexisat6 regex.test('foobar')//false //regex.lastIndexisat0 //(...andsoon) SpecificationsSpecificationECMAScriptLanguageSpecification#sec-regexp.prototype.testBrowsercompatibilityBCDtablesonlyloadinthebrowserSeealso RegularExpressionschapterinthe JavaScriptGuide RegExp RegExp.prototype Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:May17,2022,byMDNcontributors
延伸文章資訊
- 1Regex Tester and Debugger Online - Javascript, PCRE, PHP
Regular Expression Tester with highlighting for Javascript and PCRE. Quickly test and debug your ...
- 2Free Online Regular Expression Tester - FreeFormatter.com
This free regular expression tester lets you test your regular expressions against any entry of y...
- 3About Validation (Regex) - Contentstack
- 4Regex Explanation ^.*$ [duplicate] - Stack Overflow
- 5RegExp.prototype.test() - JavaScript - MDN Web Docs
The test() method executes a search for a match between a regular expression and a specified stri...