正则

67 阅读1分钟
  1. 驼峰转下划线

       let str = abcStringQxx;
       function lowCase(str){
       
       return str.replace(/([A-Z])/g,function(match,group1){
           return '_'+group1.toLowerCase()
       })
       }
       
  1. 下划线转驼峰
        let str = str_abc_ax;
        function Upcase(str){
        return str.replace(/_([a-z])/g,function(match,group1){
        return group1.toUpperCase();
        })
        
        }
  1. 手机号替换
   function replacePhone(phone){
       return phone.replace(/(\d{3})(\d{4})(\d{4})/g,function(match,g1,g2,g3){
       return g1+'****'+g2});
   }
  • \w [A-z0-9_]
  • \d [0-9]
  1. ^
  • 在【】外部,表示匹配以xxx开头
  • 在【】内部,表示除了内部的所有元素以外其他的元素
  1. 模版字符串匹配
let str = 'my name is ${name},coming from ${city}';
let data = {
name: 'manba',
city:'能源之城',
}
function moban(str,data){
// replace 并不会改变原有字符串,会返回一个新的字符串。
let res = str.replace(/\$\{(\w*)\}/g,function(match,group1){
return data[group1];
})

}

  1. |
  • 在[] 内部代表一个 字符,表示匹配该'|',
  • 在[]外部表示 或
    /^[about|cont]$/ 匹配的是 a b o u t c n |  以任意某个开头 且以其结尾的字符
  1. 贪婪匹配 返回最小的符合情况的值 /<.*?>/g

image.png