javascript 正则替换通讯录特殊字符


javascript 正则替换通讯录特殊字符,示例数据如下:

+86 18612345678
8613898765421
135-1234-5678
+8615145698763
+86 151-4569-8763

使用 javascript 统一将上述不同格式数据整理为标准11位数字手机号,如下:
18612345678

不是伸手党,实在没思路,请指示!

javascript正则 JavaScript

诺德皇家卫士 8 years, 11 months ago

 var reg = /[+-\s]/g,
    mobileReg = /^(13|15|18)\d{9}$/,
    res = [], tempStr;

var phones = [ ' +86 12345678910 ', ' 8613898765421', '135-1234-5678', '+8615145698763', '+86 151-4569-8763']

for (var i = 0; i < phones.length;i++) {
    tempStr = phones[i].trim().replace(reg, '').slice(-11);
    if (mobileReg.test(tempStr)) {
        res.push(tempStr)
    }
}

console.log(res);  // ["13898765421", "13512345678", "15145698763", "15145698763"]

其实我是外国人 answered 8 years, 11 months ago


 <textarea name="" id="phones" cols="30" rows="10">
+86 18612345678
8613898765421
135-1234-5678
+8615145698763
+86 151-4569-8763
</textarea>


<script type="text/javascript">
    var p = document.getElementById('phones'),
        txt = p.value;//得到手机号

    //将非数字的替换为空, 将以86开头后面跟11位数字的,替换为后面的11位数字
    p.value = txt.replace(/[-+ ]/g, '').replace(/^86(\d{11})/gm, '$1');
</script>

运行效果: http://jsbin.com/razolodoko/1/

茶树菇香鸡 answered 8 years, 11 months ago

简单的字符替换 + 字符截取

str.replace(/[+-\s]/g, '').slice(-11);

无聊的水水 answered 8 years, 11 months ago

Your Answer