Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 246
vishnu Avatar asked Oct 29 '18 10:10

vishnu


People also ask

How to remove whitespace in JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.

How to remove space at the end of string in JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How to remove ZERO-WIDTH SPACE characters from a JavaScript string?

In this article, we’ll look at how to remove zero-width space characters from a JavaScript string. To remove zero-width space characters from a JavaScript string, we can use the JavaScript string replace method that matches all zero-width characters and replace them with empty strings.

How to remove country code from phone number?

Then you can remove it using your preferred way like String PhoneNumber = phoneNo.replaceAll ("countryCode ", "" ); Thanks for contributing an answer to Stack Overflow!

How to remove the empty space from a string in JavaScript?

The second string can be given as empty string so that the empty space to be replaced. The first parameter is given a regular expression with a space character (” “) along with the global property. This will select every occurrence of space in the string and it can then be removed by using an empty string in the second parameter.

How to remove leading zeros from a number in JavaScript?

How to remove leading zeros from a number in JavaScript? How to remove leading zeros from a number in JavaScript? Use parseInt () to remove leading zeros from a number in JavaScript.


2 Answers

var value = "+91 99 16 489165";
var number = value.replace(/\D/g, '').slice(-10);
like image 196
Eugene Mihaylin Avatar answered Sep 23 '22 21:09

Eugene Mihaylin


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, "");
}
like image 33
Jelle Bruisten Avatar answered Sep 22 '22 21:09

Jelle Bruisten