正则表达式是描述字符模式的对象
为什么使用正则:
1.找数字
1 var str = "12 f13kjm54n43 43k"; 2 var arr = []; 3 4 for(var i = 0, len = str.length; i<len; i++){ 5 6 var char = str.charAt(i); 7 8 if(char >= "0" && char <= "9"){ 9 arr.push(char); 10 } 11 12 } 13 console.log(arr);
1 var str = "12 f13kjm54n43 43k"; 2 var re = /\d/g; 3 var reArr = []; 4 reArr = str.match(re); 5 6 console.log(reArr);
2.找数字(连续的)
1 var str = "12 f13kjm54n43fdf545655656 43k 323456"; 2 var arr = []; 3 var tmp = ""; 4 5 for(var i = 0, len = str.length; i<len; i++){ 6 var char = str.charAt(i); 7 if(char >= "0" && char <= "9"){ 8 tmp += char; 9 }else{ 10 if(tmp){ 11 arr.push(tmp); 12 } 13 tmp = ""; 14 } 15 } 16 17 if(tmp){ 18 arr.push(tmp); 19 } 20 21 console.log(arr);
1 var str = "12 f13kjm54n43fdf545655656 43k 323456"; 2 var reArr = []; 3 var re = /\d+/g; 4 reArr = str.match(re); 5 6 console.log(reArr);
正则的定义:
定义:new RegExp(规则,选项)
1 var str = "skfjudfjhgqafdsghj"; 2 var re = new RegExp("a"); 3 4 alert(str.indexOf("a")); 5 alert(str.search(re));
选项:img(i:忽略大小写,m:多行,g:全局)
1 var str = "skfjudfjhgqafdsghj"; 2 var re = new RegExp("A","i"); 3 4 alert(str.indexOf("A")); 5 alert(str.search(re));