//Regular expression (emphasis)
//1. Simple regular expression
/* var reg = /a/;//Match a single a (including)
var content = "ab";
var res = reg.test(content);//If the match of the regular expression is satisfied, return true, otherwise return false
alert(res);
reg = /^a $/;//matches exactly one a
alert(reg.test(content));//false */
//2. Special characters (metacharacters)
/*
\d - a single digit 0-9 \D - matches a single non-digit
\s - a single whitespace character \S - a single non-whitespace character
\w - a single word character (number, letter , underscore) \W - non-word
. - Match any one character
Quantity: {m}-exactly m, {m,n}-at least m and at most n, {m, }-At least m and at most n
+At least 1,?0 or 1,*0 or more
*/
//Match 6-digit bank password
var bankReg = /^\d{6}$/;
var password = "12345a";
//alert(bankReg.test(password));
//Match decimals
var des = /^\d+\.\d+$/;
var price = '16.5';
//alert(des.test(price));
// 3. Set characters
//[0-9] a single number, [a-z] a single lowercase letter, [A-Z] a single uppercase letter
//Matching identifier: composed of numbers, letters, underscores, $, cannot Starts with a number, unlimited length
var flagReg = /^[a-zA-Z_\$][\w\$]*$/;
var name = "7n";
/* if (!flagReg.test(name)){
alert(name+'is an illegal identifier');
} */
//4.Group()
//Match ip address 192.168.1.130
var ipReg = /^(\d{1,3}\.){3}\d{1,3}$/;
var ip = '192.168.1.130';
//alert(ipReg.test(ip));
//5.|
//Match three primary colors (red, green, blue)
var regColor = /^(red| green|blue)$/;
var color = "blu";
//alert(regColor.test(color));
//6. String support for regular expressions match(),search()
var text="wegearghellogreghElloEogeghello40t43thg5";
//match(): Find a match for one or more regular expressions
var arr = text.match(/hello/gi );//If there is no global flag g, only one match is performed; the flag i means that case is ignored
for(var i=0;i
}
//search(): Retrieve substrings that match the regular expression and return the starting position of the first matching substring
var index = text. search(/hello/);
alert(index);
The above is the detailed content of How to use regular expressions in js?. For more information, please follow other related articles on the PHP Chinese website!