The creation of regular expressions
JS Regular expressions are created in two ways: New RegExp () and direct literals.
Use RegExp object to create var regobj = new RegExp ("(^\\s+) | ( \\s+$) "," G "); Double slash indicates transfer//using direct literal to create var regstr =/(^\s+) | (\s+$)/g;
Where G is a full-text match, and the associated I and m,i indicate that the match ignores case, M is a multiline match, and if multiple conditions are used at the same time, it is written as: GMI
The difference between (), [], {}
The function of () is to extract the matching string. Several () in the expression will get several corresponding matching strings. For example (\s+) A string that represents a contiguous space.
[] is the range of characters that defines the match. For example [a-za-z0-9] means that character text is matched to English characters and numbers.
{} is generally used to indicate the length of a match, such as \d{3} to match three digits, \d{1,3} to match the number of digits, \d{3,} to match 3 or more digits.
Note:/\d{3}/.test (1234), true; This is because when 123 of 1234 matches a regular expression, it returns true. The correct wording should be:/^\d{3}$/
^ and $
^ matches the beginning of a string, such as (^a) matches a string that begins with the letter A
$ matches the end of a string, such as (b$), that matches a string ending with the letter B
^ Another function is to reverse, such as [^xyz] means that the matching string does not contain XYZ
Note the problem:
1, if ^ appears in [] is generally expressed in reverse, and appear in other places is the beginning of the matching string
2, ^, and $ mates can effectively match the full string:/d+/.test (' 4xpt '), True, and/^\d+$/.test (' 4XPT ')->false
\d \s \w.
\d matches a nonnegative integer equivalent to [0-9]
\s matches a white space character
\w matches an English letter or number, equivalent to [0-9a-za-z]
. Matches any character except newline characters, equivalent to [^\n]
* + ?
* Indicates a match for the preceding element 0 or more times, e.g. (\s*) to match 0 or more spaces
+ means match the preceding element 1 or more times, for example (\d+) to match a string consisting of at least 1 integers
? Matches the preceding element 0 or 1 times, equivalent to {0,1}, such as (\w?) matches a string of up to 1 letters or numbers
$ and \1
The $1-$9 stores the results of the extraction of the most recent 9 regular expressions in the regular expression, which are arranged sequentially in the order in which they appear in the sub-match. The basic syntax is: REGEXP. $n, these properties are static, except that the second parameter in replace can omit RegExp, and all other uses are added REGEXP
Using REGEXP Access/(\d+)-(\d+)-(\d+)/.test ("2016-03-26") regexp.$1/ /2016regexp.$2/ /03regexp.$3 // 26//use "2016-03-26" in Replace. Replace (/(\d+)-(\d+)-(\d+)/, "$-$-month-$-$-day")
March 26, 2016
\1 refers to a back reference, which is the content in the regular expression, from left to right, 1th (), and so on, and so on, \2 represents the 2nd (), and the whole expression.
Matches the date format, and the \1 in the expression represents a repetition (\-|\/|.) var rgx =/\d{4} (\-|\/|.) \d{1,2}\1\d{1,2} "/rgx.test (" 2016-03-26 ")//true
The difference between the two is that \ n can only be used in expressions, and $n can only be used outside of an expression.
Test, Match
Most of the preceding is the syntax of the JS regular expression, and test is used to detect whether the string matches a regular expression, if the match will return true, and vice versa returns false
/\d+/.test ("123"); True/\d+/.test ("abc"); False
Match is the result of getting a regular match, returned as an array
"186a619b28". Match (/\d+/g); ["186", "619", "28"]
Replace
Replace itself is a method of a JavaScript string object that allows two parameters to be received:
Replace ([regexp| String],[string| Function])
The 1th argument can be a normal string or a regular expression
The 2nd argument can be a normal string or a callback function
If the 1th parameter is RegExp, JS will first extract the results of the regexp match, and then replace the matching result with the 2nd parameter one after the other.
If the 2nd parameter is a callback function, each match to one result is recalled once, each callback will pass the following parameters:
Result: The results of this match are,... $9: there are several () in the regular expression, a few arguments are passed, and $1~$9 represents the result of each () extract in this match, up to 9 offset: Record the start of this match source: Accept the matching original string
Common Classic cases:
1. Implement the Trim function of the string to remove spaces on both sides of the string
String.prototype.trim = function () { //mode one: Replace each result that matches to return This.replace (/(^\s+) | ( \s+$)/g,function () { return ""; }); Mode two: Same principle as mode one return This.replace (/(^\s+) | ( \s+$)/g, ');};
^\s+ represents a continuous white space character that begins with a space, \s+$ represents a continuous white space character that ends with a space, plus () extracts the result of the match, because it is | , so this expression will match up to two result sets and then perform two substitutions:
String.prototype.trim = function () { /** * @param rs: matching result * @param $: 1th () Extract result * @param $: 2nd () Extract result * @param offset: match start position * @param Source: Original String * /This.replace (/(^\s+) | ( \s+$)/g,function (rs,$1,$2,offset,source) { //arguments each element corresponds to a parameter console.log (arguments); });}; " ABCD ". Trim (); Output: [" "," ", Undefined, 0," ABCD "]//1th match result [" ", Undefined," ", 5," ABCD "]//2nd match result
2. Extract parameter names and parameter values from the browser URL to generate an Key/value object
function Geturlparamobj () { var obj = {}; Gets the parameter part of the URL var params = window.location.search.substr (1); [^&=]+ represents a continuous character without & or =, plus () is the extraction of the corresponding string params.replace (/([^&=]+) = ([^&=]*)/gi,function (rs,$1,$2 { obj[$1] = decodeuricomponent ($); }); return obj;}
/([^&=]+) = ([^&=]*)/gi each match is a complete key/value, shaped like xxxx=xxx, whenever a match to one such result is executed callback, and pass the match to the key and value, corresponding to $ and $
3. Inserting a new string at the specified position in the string
String.prototype.insetAt = function (str,offset) {
offset = offset + 1; Use the REGEXP () constructor to create a regular expression var regx = new RegExp ("(^.{" +offset+ "})"); Return This.replace (REGX, "$" +str);}; " ABCD ". Insetat (' xyz ', 2); Insert Xyz>> "Abcxyzd" in the C-word specifier
When offset=2, the regular expression is: (^.{ 3}). represents any character except \ n, {3} means matching the first three consecutive characters, plus () extracts the match to the result, and replaces the matched result with a new string with replace, as follows: result = result +str
4. Convert phone number 12988886666 to 129****6666
function Telformat (tel) { Tel = String (tel); Way One return Tel.replace (/(\d{3}) (\d{4}) (\d{4})/,function (rs,$1,$2,$3) { return $1+ "* * *" +$3 }); Mode two return Tel.replace (/(\d{3}) (\d{4}) (\d{4})/, "$1****$3");}
(\d{3}\d{4}\d{4}) can match the full phone number, and extract the first 3, 4-7 and 8-11 bits respectively, "$1****$3" is to replace the 2nd match with a new string, and then replace the full phone number.
5. Implement HTML encoding, Escape </> "&" characters to avoid XSS attacks
function HtmlEncode (str) { //Match </> & ' return str.replace (/[<> "&\/']/g, function (RS) { C2/>switch (RS) {case "<": return "<"; Case ">": return ">"; Case "&": return "&"; Case "\" ": Return" " "; Case "/": return "& #x2f;" Case "'": return "& #x27;" } });}
JS Regular Expression Refinement