JavaScript remove spaces, country code and begging zero from contact number

Viewed 9310

I have contact list and need to remove the country code(+91), spaces between number and zero(prefix with zero) from the mobile number. And it should contain only 10 digits.

I have tried using Regex in the following way, but it removing only spaces from the number.

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);
6 Answers
var value = "+91 99 16 489165";
var number = value.replace(/\D/g, '').slice(-10);

You could use a string.substr if u know for sure theres a country code after a "+" or "0".

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, "");
}
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);

I hope this helps:

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);
}

Here is a regex that I use to only remove the country code portion of the phone number:

var mobile = value.replace(/^\+[0-9]{1,3}(\s|\-)/, "");

United States:

+1 345 345 7678

+1-453-677-7655

India:

+91 99 16 489165

It works with all of the country codes listed on this website if they start with a "+" sign in your data: https://countrycode.org/

remove spaces and get the last 10 digits.

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