Javascript 字符串 match() 方法返回错误 "Uncaught TypeError: Cannot read property ' toString' of null"

标签 javascript jquery reactjs

  • 下面是我的代码,用于将电话号码字符串与正则表达式匹配并返回 与电话号码匹配的字符串格式。它采用电话号码 “+12-787878”格式,正则表达式匹配后返回“+12”。

  • 此代码在 chrome、firefox 上运行良好,但只能在一个开发人员上运行
    机器返回错误,如“Uncaught TypeError: Cannot read
    属性“toString”为 null”。

Check out below code.
var countryDialCode = phone ?phone.match(CONSTANTS.EXTRACT_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 数据类型调用 toString()。您可以按如下方式修复此错误。

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

关于Javascript 字符串 match() 方法返回错误 "Uncaught TypeError: Cannot read property ' toString' of null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408042/

相关文章:

javascript - 如何从php中的数据库完整路径名中获取每个用户的图像

php - 州和国家选择框 - 最好的方法是什么?

jquery - 检查 span 元素是否存在,然后动态添加 div

javascript - 在 React 中复制并移动组件

javascript - 无法检索在 servlet 中设置的值

javascript - 如何通过从对象数组更新特定对象中的数组来更新状态?

javascript - 如何修复 'Objects are not valid as a React child'

javascript - 我如何 Jest 模拟 Date.toLocaleDateString?

javascript - 奇怪的 "Uncaught TypeError: String is not a function"错误

javascript - 升级 jQuery 后出现类型错误