Javascript字符串match()方法返回错误“”;未捕获的类型错误:无法读取属性'toString
Javascript string match() method returning error "Uncaught TypeError: Cannot read property 'toString' of null"
-
下面是我将电话号码字符串与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;
}
}
试试看,这样行不行?
相关文章:
- 是否排除节点中错误堆栈的第一行?/节点中的自定义错误类型
- 模版启动错误-类型错误(“参数”url'必须是字符串,而不是“+类型的url”)
- 我们可以得到jQueryValidate错误类型吗
- 错误“类型错误: $(..).孩子不是一种功能”
- 谷歌图表绘制()方法错误类型时给定数据表
- 错误:类型错误: $(..).选择选择器不是使用 requireJS 加载的函数库
- 我收到一个错误:类型错误:在使用解析 API 更新用户对象时未定义 e.changes.如何解决这个问题
- 随机子字符串错误?“类型错误:在对象中找不到函数子字符串.".
- 无法理解为什么代码给出错误:类型错误:0 是只读的
- 为什么我收到jQuery错误“类型错误:$(..).在以下场景中,Live 不是一个函数
- 角度类型提前异步结果 - 收到错误“类型错误:无法使用'in'运算符搜索 ..在..".
- 在 Node.js 服务器内发出异步请求错误:“类型错误:对象 #<对象> 没有方法'_implicitHeader'”
- JQuery 错误: 类型错误: 'undefined' 不是一个函数
- 在 Angular 应用程序上收到错误:类型错误:无法读取未定义的属性“then”
- 获取错误类型错误:onOk 不是一个函数
- 如何检测带有源的音频标记的错误类型
- Javascript-错误:inQuery Parse.com的102错误类型
- Javascript变量作用域问题-错误:类型错误:this.graphics未定义
- 捕获脚本错误 - 类型,行和文件
- jquery错误类型错误:值不是对象..split(& # 39; & # 39;)