下面是我的代码,用于将电话号码字符串与正则表达式匹配并返回 与电话号码匹配的字符串格式。它采用电话号码 “+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/