手记

正则表达式学习笔记(4)- 常用正则

4. 常用正则表达式

4.1 去除首尾字符串空格(trim)

var str = ' I am a cat. ',
    reg = /^\s+|\s+$/;

console.log(str.replace(reg, ''));  // I am a cat.

4.2 匹配电话号码

var str = '0715-85624582-234',
    str2 = '027-51486325',

    // \d{3,4} 3-4位区号
    // \d{8} 8位电话号码
    // (-(\d{3,4}))? 可能存在3-4位分机号
    reg = /^(\d{3,4})-(\d{8})(?:-(\d{3,4}))?$/;

console.log(str.match(reg));    // [ '0715-85624582-234', '0715', '85624582', '234', index: 0, input: '0715-85624582-234' ]
console.log(str2.match(reg));   // [ '027-51486325', '027', '51486325', undefined, index: 0, input: '027-51486325' ]

4.3 匹配手机号码

var str = '17985642351',
    reg = /^1[3|4|5|7|8]\d{9}$/;

console.log(str.match(reg));    // [ '17985642351', index: 0, input: '17985642351' ]

4.4 匹配邮箱

var str3 = 'yuzhongzi_91.xiao@sina.com',
    pattern3 = /^(?=[a-zA-Z])([\w\d-]+)(?:\.([\w\d-]+))*?@([a-zA-Z0-9]+)(?:\.([a-zA-Z]+))+$/;

// [ 'reg.xiao91@gmail.com', 'reg', 'xiao91', 'gmail', 'com', index: 0, input: 'reg.xiao91@gmail.com' ]
console.log(str3.match(pattern3));

4.5 限制文本框只能输入数字和小数点(二位小数点)

var reg = /^\d*\.?\d{0,2}$/;

console.log(reg.test('.4'));        // true
console.log(reg.test('3'));         // true
console.log(reg.test('3.3333'));    // false

4.6 匹配中文

var str = '223我是abc一只猫234',
    reg = /[\u4E00-\u9FA5\uf900-\ufa2d]/g;

console.log(str.match(reg));    // [ '我', '是', '一', '只', '猫' ]

4.7 匹配标签中的内容

var str = '<div>java<p>hello</p>script</div>',

    // 或者为 /<div>(.*)<\/div>/ 但不能匹配'\n'
    // /<div>((?:.|\s)*)<\/div>/
    reg = /<div>[\s\S]*<\/div>/;

if (reg.test(str)) {
    console.log(RegExp.$1);     // java<p>hello</p>script
}

4.8 匹配带有属性的标签

var str = '<div class="test" id="test" data-id="2345-766-sd24">hello</div>',
    reg = /<([a-zA-Z]+)(\s*[a-zA-Z-]*?\s*=\s*".+?")*\s*>([\s\S]*?)<\/\1>/;

if (reg.test(str)) {
    console.log(RegExp.$3);     // hello
}

4.9 将数字转化为中文大写字符

var arrs = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"],
    reg = /\d/g,
    str = '135268492580',
    res;

res = str.replace(reg, function(v) {
   return arrs[v];
});

console.log(res);   // 壹叁伍贰陆捌肆玖贰伍捌零

4.10 查找链接

var str = '<a href="http://www.rynxiao.com">rynxiao.com</a>',
    reg = /http:\/\/(?:.?\w+)+/;

console.log(str.match(reg)[0]); // http://www.rynxiao.com
1人推荐
随时随地看视频
慕课网APP