JavaScript中的应用

it2022-05-05  201

1.exec与g 一起使用,每次调用依次返回不同的分组2.exec 不与g一起使用,只第一个查找的分组// 将字符串转为对象var cssRe=/([a-z0-9\-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi function parseStyles(styles){var out = {}, matches; if (styles){ cssRe.lastIndex = 0;while ((matches = cssRe.exec(styles))){ out[matches[1]] = matches[2] || ''; }}return out; } parseStyles("font-size:12px;border:1px solid gray;") //{font-size:12px;border:1px solid gray;}

 2.常用的正则表达式

/\S/ --非空\w 匹配任何字类字符,包括下划线。与“[A-Za-z0-9_]”等效。

3.replace 与分组正则一起使用

1.将手机号12988886666转化成129 8888 6666function telFormat(tel){ tel = String(tel); //方式一 return tel.replace(/(\d{3})(\d{4})(\d{4})/,function (rs,$1,$2,$3){ return $1+" "+$2+" "+$3 }); //方式二 return tel.replace(/(\d{3})(\d{4})(\d{4})/,"$1 $2 $3"); }ps:rs 表示原数据 即12988886666

 4.replace 不与分组一起使用

1.实现函数escapeHtml,将<, >, &, " 进行转义function escapeHtml(str) { //匹配< > " & return str.replace(/[<>"&]/g, function(rs) { switch (rs) { case "<": return "<"; case ">": return ">"; case "&": return "&"; case "\"": return """; } }); } ps:rs 表示匹配的数据  

 

转载于:https://www.cnblogs.com/haigui-zx/p/6559388.html

相关资源:JavaScript应用程序经典实例.pdf

最新回复(0)