Test method
Returns a Boolean value that indicates whether the given regular expression is matched in the string being searched.
Rgexp.test (str)
Parameters
Rgexp
Required option. A regular expression object that contains the regular expression pattern or the available flags.
Str
Required option. The string on which to test the lookup.
Description
The test method checks whether the string matches the given regular expression pattern, returns true if it is, or returns false.
Each regular expression has a lastindex property that records where the last match ended
The code is as follows |
Copy Code |
var re =/^[1-9]d{4,10}$/gi; var str = "123456"; Alert (Re.test (str)); Returns True |
After performing the above test
We can eject
The code is as follows |
Copy Code |
alert (Re.lastindex); Pop up 6 |
That represents the last time after the 6th character has ended
The next time you call test, the search will continue from the 6th character.
Workaround, set the Lastindex property of the regular expression to 0
The specific code is as follows:
The code is as follows |
Copy Code |
<script type= "Text/javascript" > var re =/^[1-9]d{4,10}$/gi; var str = "123456"; Alert (Re.test (str)); Returns True str = "1234567"; re.lastindex=0; Alert (Re.test (str)); Returns True </script> |
Example 2
The code is as follows |
Copy Code |
function Testdemo () { var r, re; Declare a variable. var s = "I"; re =/i/ig; Creates a regular expression pattern. document.write (Re.test (s) + "<br/>"); Returns a Boolean result. document.write (Re.test (s) + "<br/>"); document.write (Re.test (s)); } Testdemo (); Output results:
True False True |
JavaScript forms Validate Email mailboxes, determine whether an input is email, and implement it through regular expressions.
Check email Email
The code is as follows |
Copy Code |
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" > <HTML> <HEAD> <title>javascript form Verification Email Email </TITLE> </HEAD> <BODY> <script language= "JavaScript" > function Check () { var Email=document.getelementbyid ("email"). Value; var isemail=/^w+ ([-.] w+) *@w+ ([.-]w+) *.w{2,4}$/; if (email== "") { Alert ("Please enter your email address!"); return false; } if (email.length>25) { Alert ("Length too long"); return False } if (!isemail.test (email)) { Alert ("Not a Mailbox"); return false; } } </script> <form method=post action= "" Onsubmit= "return Check ()" > <input type= "text" name= "email" ><input type= "Submit" > </FORM> </BODY> </HTML> |