Js Regular Expression Learning 1
I. js-Regular Expression
Is an object that describes the character mode. The RegExp class of ECMAScript indicates a regular expression. Regular Expressions are mainly used to verify the input data of the client. After the user enters the form and clicks the button, the form is sent to the server.
Ii. Create a regular expression
1. Use the new operator to create
Var box = new RegExp ('box'); // The first parameter is the pattern string (two backslash values are the literal representation of the regular expression)
Var box = new RegExp ('box', 'ig '); // optional mode modifier for the second parameter (I: case-insensitive; g: Global match; m: multi-row matching)
2. Create with literal representation (commonly used)
Var box =/Box/; // use a regular expression in the literal Mode
Var boa =/box/ig; // Add a pattern modifier after the second slash
Iii. Test Regular Expressions
1. Use the test () method
For example:
Var pattern = new RegExp ('box'); // Mode
Var str = 'box'; // string
Alert (pattern. test (str); // The returned value is false, Which is case-insensitive.
Var pattern = new RegExp ('box, 'I'); // case sensitive
Var str = 'box'; // string
Alert (pattern. test (str); // return true
Var pattern = new RegExp ('box, 'I'); // case sensitive
Var str = 'this is a box'; // string
Alert (pattern. test (str); // The returned value is true. Whether the string contains regular expressions in the Mode
2. Use exec () to return the matching Array
Var pattern =/Box/I;
Var str = 'ish is a box ';
Alert(pattern.exe c (str); // matches the returned array; otherwise, null is returned.
IV,
1. Use the match method to obtain the matching Array
Var pattern =/box/ig; // global search
Var str = "this is a bax !, That is a box too ';
Alert (str. match (pattern); // matches two boxes;
Alert (str. match (pattern). length); // gets the length of the array.
Var pattern =/box/I; // Global is not enabled
Var str = 'this is a bax !, That is a box too ';
Alert (str. match (pattern); // returns an array after matching the first string;
2. search for matched data
Var patern =/box/ig;
Var str = 'this is a bax !, That is a box too ';
Alert (str. search (pattern); // returns the first matched position; otherwise,-1 is returned;
3. replace the matched data with replace
Var patern =/box/ig;
Var str = 'this is a bax !, That is a box too ';
Alert (str. search (pattern, 'Tom '); // Replace box with Tom
Var patern =/box/I; Global is not enabled
Var str = 'this is a bax !, That is a box too ';
Alert (str. search (pattern, 'Tom '); // Replace the first box with Tom
4. split the String Array Using split
Var pattern = // ig;
Var str = 'this is a bax !, That is a box too ';
Alert (st. split (pattern); // splits spaces into arrays.