JavaScript去除联系电话中的空格、国家代码和前导零

6

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

我尝试使用以下方式的正则表达式,但它只会从号码中删除空格。

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);
7个回答

17
var value = "+91 99 16 489165";
var number = value.replace(/\D/g, '').slice(-10);

2
如果您确定在“+”或“0”后面有一个国家代码,可以使用string.substr。
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, "");
}

1
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
我希望这可以帮助你:

var value = "+91 99 16 489165";
var mobile = "";

//First remove all spaces:
value = value.replace(/\s/g, '');


// If there is a countrycode, this IF will remove it..
if(value.startsWith("+")){
  var temp = value.substring(3, value.length);
  mobile = "0"+temp;
  
  //Mobile number:
  console.log(mobile);
}


// If there is no countrycode, only remove spaces
else{
  mobile = value;
  
  //Mobile number:
  console.log(mobile);
}


0
使用正则表达式仅删除印度手机号码的空格前缀。
"919511708928".replace(/\D/g, '').slice(-10);

0

去除空格并获取最后10位数字。

str.replaceAll(" ","").slice(-10)

0
这是一个正则表达式,用于仅移除电话号码的国家代码部分:
var mobile = value.replace(/^\+[0-9]{1,3}(\s|\-)/, "");

美国:

+1 345 345 7678

+1-453-677-7655

印度:

+91 99 16 489165

如果您的数据以“+”号开头,并且符合此网站上列出的所有国家代码,它将可以正常工作: https://countrycode.org/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接