JS regular expression related methods (regular learning notes 1)

Time:2021-4-16
Copy codeThe code is as follows:
var str=”abcdefghijklnabcdefghijklmnabcabdefghijklmn”;
re=/a/g;

alert(re.test(str));
//The test method call returns true and false to indicate whether a matching character is found in the specified string — true

alert(re.exec(str));
//Returns the first string in the string that matches the expression — A

alert(str.match(re));
//Returns an array, each of which matches the array of expressions — [a, a, a] note that the global variable g must be used for regularization

alert(str.search(re))
//Return the first occurrence position of the matching regular, starting from 0, and return – 1 if not found — 0 * is a bit like indexof*

alert(str.replace(re,”b”))
//It’s easy to replace * this one. Needless to say*

alert(str.split(re)[0])
//Split is generally used to divide a string into an array and return an array object, where the value of the 0 subscript of the array is returned

Regularization can simplify many operations. Especially in the form of data validation.