Javascript字符串match()方法返回错误“”;未捕获的类型错误:无法读取属性'toString

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

本文关键字:错误 类型 读取 toString 属性 match 字符串 方法 返回 Javascript      更新时间:2023-09-26
  • 下面是我将电话号码字符串与Regex匹配并返回的代码phoneNumber中匹配的字符串格式。它需要phoneNumber"+12-7787878"格式,正则表达式匹配后返回"+12"。

  • 此代码在chrome、firefox上运行良好,但仅适用于一个开发人员
    机器返回错误,如"未捕获类型错误:无法读取
    属性'toString'为null".

查看下面的代码
var countryDialCode=电话?phone.match(CONSTANTS.EEXTRACT_DIAL_NUMBER,''(.toString((:'';

 CONSTANTS.EXTRACT_DIAL_NUMBER = '/^[+]'d+/g';
 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方法在字符串不匹配时返回null,因此不能在null dataType上调用toString()。您可以按如下方式修复此错误。

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

.match需要regexp并返回数组作为输出,因此最好将regexp传递给match方法

CONSTANTS.EXTRACT_DIAL_NUMBER = /^[+]'d+/g;
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): [''];
        countryDialCode = countryDialCode[0];
        this.refs.contactComponent.refs.cellNumber.refs.input.value = countryDialCode;
    }
}

试试看,这样行不行?

相关文章: