Original: http://www.javascriptkit.com/javatutors/re.shtml
Verifying the user's input is something that every software developer has to do.
Regular expressions and patterns
How do you use regular expressions in JavaScript? There are two ways of doing this:
1) literal syntax.
2) When you need to build a regular expression dynamically, you can use the RegExp () constructor.
The literal syntax is as follows:
var regularexpression =/pattern/;
The RegExp () constructor method is as follows:
var regularexpression = new RegExp ("pattern");
The RegExp () method allows you to dynamically construct a search pattern with a string, which is a very useful method, especially if the implementation cannot know what the pattern is.
[Original sentence: the RegExp () method allows you to dynamically construct the search pattern as a string, and was useful when the pattern is not known ahead of time.]
Using a regular expression to validate a string, you must define a pattern string as the condition for the search, and then use a related string method to represent the action (Ie:search, replace etc).
Patterns are defined by using literal strings literal characters (string literal characters) and metacharacters (metacharacters).
For example, the following regular expression is judged to contain a valid 5-bit United States ZIP code string.
<Scripttype= "Text/javasript">functioncheckpostal () {varRe5digit= /^\d{5}$/; //Regular expression defining a 5 digit numberNote that there is an error in the original instance code, the original text is assigned, correct as followsif(Document.myform.myinput.value.search (re5digit)=== -1){ //if match failedAlert ("Please enter a valid 5 digit number inside form."); }}</Script><formname= "MyForm"><inputtype= "text"name= "Myinput"size= " the" /><inputtype= "button"OnClick= "Checkpostal ()"value= "Check" /></form>
Parse the regular expression used above, which is used to check a string containing 5 significant digits and can only be a 5-digit number.
var reg5digit =/^\d{5}$/;
- ^ denotes the beginning of the string, using the ^ metacharacters requires that the match be matched from the beginning
- \d represents a numeric character, followed by {5} meaning that it must be a 5-bit sequential numeric character
- $ represents the end of the string, using the $ metacharacters required to match after this string ends
Translated to 中文版, this pattern states: "Starting at the beginning of the string there must is nothing other than 5 di Gits. There must also is nothing following those 5 digits. "
In English, this pattern declares: "The beginning of the string, except for 5 digits, cannot be another character, and the 5-digit child cannot have any characters after it."
Http://www.javascriptkit.com/javatutors/re2.shtml
[Label] Translation [JavaScript Regular Expression] JavaScript Regular Expressions