Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")));
    }
});
like image 368
HasanG Avatar asked Jan 02 '12 02:01

HasanG


3 Answers

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").

like image 124
aeskr Avatar answered Nov 06 '22 07:11

aeskr


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

like image 43
Ansel Santosa Avatar answered Nov 06 '22 08:11

Ansel Santosa


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

like image 29
ThinkingStiff Avatar answered Nov 06 '22 09:11

ThinkingStiff