正则表达式实例

商品计价的千分位分隔符转换

1
return total.toString().replace(/\B(?=(\d{3})+$)/g, ',')

去除字符串的空格

  1. 字符串原生trim方法,只能去除两侧空格,返回新字符串
  2. replace正则匹配
    • 去除所有空格:str = str.replace(/\s*/g,"")
    • 去除两侧空格:str = str.replace(/^\s*|\s*$]/g,"")
    • 去除左侧空格:str = str.replace(/^\s*/,"")
    • 去除右侧空格:str = str.replace(/\s*$/,"")

中文、英文、数字但不包括下划线等符号

  • 中文:^[\u4e00-\u9fa5]{0,}$
  • 中文、英文、数字:^[\u4e00-\u9fa5A-Za-z0-9_]+$(包括下划线),[\u4e00-\u9fa5A-Za-z0-9]+$/[\u4e00-\u9fa5A-Za-z0-9]{2,20}$(不包括下划线)