首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript从联系号码中删除空格、国家代码和求援零

JavaScript从联系号码中删除空格、国家代码和求援零
EN

Stack Overflow用户
提问于 2018-10-29 18:07:43
回答 6查看 5.5K关注 0票数 5

我有联系人列表,需要删除国家代码(+91),数字之间的空格和零(前缀为零)从手机号码。并且它应该只包含10位数字。

我试着用下面的方法使用正则表达式,但它只删除了数字中的空格。

代码语言:javascript
复制
var value = "+91 99 16 489165";
var mobile = '';
if (value.slice(0,1) == '+' || value.slice(0,1) == '0') {
    mobile = value.replace(/[^a-zA-Z0-9+]/g, "");
} else {
    mobile = value.replace(/[^a-zA-Z0-9]/g, "");
}

console.log(mobile);
EN

回答 6

Stack Overflow用户

发布于 2018-10-29 18:10:04

代码语言:javascript
复制
var value = "+91 99 16 489165";
var number = value.replace(/\D/g, '').slice(-10);
票数 12
EN

Stack Overflow用户

发布于 2018-10-29 18:18:36

如果你确定"+“或"0”后面有国家代码,你可以使用string.substr。

代码语言:javascript
复制
var value="+91 99 16 489165";
var mobile = '';
if(value.charAt(0) == '+' || value.charAt(0)=='0'){
    mobile = value.replace(/[^a-zA-Z0-9+]/g, "").substr(3);
}
else {
    mobile = value.replace(/[^a-zA-Z0-9]/g, "");
}
票数 2
EN

Stack Overflow用户

发布于 2018-10-29 18:18:13

代码语言:javascript
复制
var value="+91 99 16 489165";
// Remove all spaces
var mobile = value.replace(/ /g,'');

// If string starts with +, drop first 3 characters
if(value.slice(0,1)=='+'){
       mobile = mobile.substring(3)
    }

// If string starts with 0, drop first 4 characters
if(value.slice(0,1)=='0'){
       mobile = mobile.substring(4)
    }

console.log(mobile);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53043128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档