Shtarley
Shtarley

Reputation: 391

Using javascript ".replace" to format a phone number?

I have a phone number stored in a variable and I want to format this number to include the country code. Right now I have this:

var PhoneNumber = 07xxxxxxxx;
NewNumber = PhoneNumber.replace("0", "+46");

It works great, however, currently it replaces any 0 in the number. It must only replace the 0 on the beginning of the number. For example, if the number in the variable looks like this 750xxxxxxx then it must not replace the zero, but if the 0 is at the beginning of the number (like so 07xxxxxxxx) then it must replace it.

Upvotes: 0

Views: 2252

Answers (3)

Redacks
Redacks

Reputation: 9

You can do this with a regular expression (regex)

Assumed, that your number always starts with a zero you could use this

var PhoneNumber = "0781597515" //pseudo number
var Newnumber = PhoneNumber.replace(/0/, "+46");

Upvotes: -1

esqew
esqew

Reputation: 44713

A simple way to accomplish this would be to use String.prototype.startsWith() to check if the leading character is a 0, then concatenating the +46 string to the front of PhoneNumber while removing the leading 0 with String.prototype.substring().

var PhoneNumber = "07xxxxxxxx";
var NewNumber;

if (PhoneNumber.startsWith("0")) {
  NewNumber = "+46" + PhoneNumber.substring(1);
  console.log(NewNumber);
}

Upvotes: 2

inorganik
inorganik

Reputation: 25535

Try this:

var phone = '0700000000';
var newPhone = phone.replace(/^0/, '+46 ');
console.log('new phone', newPhone);

It's the ^ that specifies you want to match the start of the string.

Upvotes: 2

Related Questions