Define the Regular:
var New REGEXP (' a '); Instantiate objects, parameters are the rules we want to make
var reg =/a/; Shorthand method
Common methods for regular use:
1, Test (): Find the content in the string that conforms to the regular, find to return true, reverse return false
Usage: Regular. Test (string);
Example: Judging whether it is a number
var str = ' 12345678 '; var // \d represents non-digital if (Reg.test (str)) { alert (' Not all numbers '); } Else { alert (' all numbers '); }
2, search (): Searching in the string matches the regular content, the search to return to the location of the occurrence (starting from 0, if the search is not just a letter, the first letter is returned), and vice versa-1
Usage: string. Search (Regular)
var str = ' Webrty '; var reg =/b/i; // I means case insensitive Console.log (Str.search (reg)); // returns 2
3. Match (): searches the string for regular content, returns the content in a successful match, formats an array, and fails returns null
Usage: string. Match (regular);
var str = ' as123msd8xx29shdkdk220nm '; var reg =/\d+/g; // match at least one number, G means global match Console.log (Str.match (reg)); // ["123", "8" , "$", "$"]
4. Replace (): Find the regular string, replace it with the corresponding string, return the replaced content
usage: string. Replace (regular, new string/callback function); (In a callback function, the first argument is the first character to match)
Example: Sensitive word filtering
var str = ' grapes do not spit on grape skins '; var reg =/Grape | skin/g; // match grape or skin, global match var str2 = str.replace (Reg, ' * '); Console.log (str2); // Eat * Don't spit * *
To implement several words corresponding to several *, you can use the callback function
varstr = ' grapes do not spit on grape skins ';varreg =/Grape | skin/g;//match grape or skin, global matchvarSTR2 = Str.replace (Reg,function(str) {//The str parameter refers to the grape for the first time, the second refers to the grape, and the third refers to the skin. varresult = '; for(vari=0;i<str.length;i++) {result+ = ' * '; } returnresult;}); Console.log (STR2); //Eat * * NOT spit * * *
JS Regular expression (1)