Kalashir Kalashir - 1 month ago 10
jQuery Question

Javascript string match() method returning error "Uncaught TypeError: Cannot read property 'toString' of null"

  • Below is my code to match phonenumber string with Regex and return
    matched string format from the phoneNumber.It takes phoneNumber in
    "+12-787878" format and after regex match returns "+12".

  • This code works fine on chrome ,firefox but only on one developer

    machine it is returning error like "Uncaught TypeError: Cannot read

    property 'toString' of null" .

Check out below code.

var countryDialCode = phone ?phone.match(CONSTANTS.EXTRACT_DIAL_NUMBER, '').toString(): '';

phone = "+91-7778889078";
expected output = "+91";

getDialCodes: function() {
var phone = SessionStore.getLoggedInUserDialCode();
if(phone && _.isEmpty(this.refs.contactComponent.refs.cellNumber.refs.input.value)) {

// Below is the code to extract numbers followed by + sign from the given phonenumber string.
var countryDialCode = phone ? phone.match(CONSTANTS.EXTRACT_DIAL_NUMBER, '').toString(): '';

this.refs.contactComponent.refs.cellNumber.refs.input.value = countryDialCode;


match method return null when string is not matched so you can not call toString() on null dataType. You can fix this error as below.

$res=phone.match(CONSTANTS.EXTRACT_DIAL_NUMBER, '');
var countryDialCode = phone ? ($res==null? '': $res.toString() ): '';