HasanG
HasanG

Reputation: 13161

Match phone country code with javascript

I'm trying to implement a javascript function to replace country code part of a phone number.

The input is +90 (533) 333 33 33 and I want to replace +90 part with javascript. I tried do write a regex but I couldn't succeed.

/^\++[a-z]+\s$/

EDIT : Final solution

$("#ddlCountry").change(function () {
    if ($("#tMobile").val() == '') {
        $("#tMobile").val("+" + $(this).find(":selected").attr("CountryCode")
        + " ");
    } else {
        $("#tMobile").val($("#tMobile").val().replace(/^(\+\d*)/,
        "+" + $(this).find(":selected").attr("CountryCode")));
    }
});

Upvotes: 5

Views: 5165

Answers (3)

ThinkingStiff
ThinkingStiff

Reputation: 65341

This is considerably faster than regular expressions.

function replaceCountryCode ( number, replaceWith ) {
    return replaceWith + number.substr( number.indexOf( ' ' ) );
};

Demo: http://jsfiddle.net/ThinkingStiff/XEBdP/
Performance: http://jsperf.com/regex-vs-indexof-replace

enter image description here

Upvotes: 2

aeskr
aeskr

Reputation: 3436

The following pattern should match any country code, assuming there's always a non-digit character between the country code and whatever number comes next: /^(\+\d*)/

var phoneNumber = "+90 (533) 333 33 33";
phoneNumber = phoneNumber.replace(/^(\+\d*)/, '+852');
alert(phoneNumber);

(Try it on JSFiddle)

Edit: Okay... this is a bit silly, you can also do this:

var phoneNumber = "+90 (533) 333 33 33";
phoneNumber = phoneNumber.replace(/^(\+)(\d*)(.*)/, '$1852$3');
alert(phoneNumber);

(Try it on JSFiddle)

I was trying to make it unnecessary to include the plus sign in the new country code, but I can't find a way of doing that other than what I've shown above. Essentially, it uses three capture groups: one for the plus sign, one for the country code, and one for the rest of the phone number. In the new country code, I sandwiched the country code itself in between $1 and $3, which translates to:

Replace the old phone number with a new phone number consisting of the first capture group (the plus sign) followed by the new country code ("852") followed by the rest of the phone number (" (533) 333 33 33").

Upvotes: 2

Ansel Santosa
Ansel Santosa

Reputation: 8444

as long as you can guarantee that your input will be in that format:

var phone = '+90 (533) 333 33 33';
    phone.replace(/^\+[0-9]{2}/,'xyz')

Before: +90 (533) 333 33 33

After: xyz (533) 333 33 33

Upvotes: 2

Related Questions