JavaScript中的应用

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 6666

function
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值