Javascript正则表达式.match()为null

时间:2011-02-15 18:30:27

标签: javascript regex

console.log(r.message); //returns "This transaction has been authorized"
if (r.message.match(/approved/).length > 0 || r.message.match(/authorized/).length > 0) {
// ^ throws the error: r.message.match(/approved/) is null

这不是在JavaScript中进行匹配的正确方法吗?

success: function (r) {
    $('.processing').addClass('hide');
    if (r.type == 'success') {
        console.log(r.message);
        if (r.message.match(/approved/).length > 0 || r.message.match(/authorized/).length > 0) {
            triggerNotification('check', 'Payment has been accepted');

            //document.location = '/store/order/view?hash='+r.hash;
        } else {
            triggerNotification('check', r.message);
        }
    } else {
        $('.button').show();

        var msg = 'Unable to run credit card: '+r.message;

        if (parseInt(r.code) > 0) {
            msg = msg+' (Error code: #'+r.code+')';
        }
        triggerNotification('x', msg);
    }
},

3 个答案:

答案 0 :(得分:17)

由于您正在获得授权消息,因此语句r.message.match(/approved/)将返回null,因此会出现问题。

按如下方式重写支票:

if (/approved|authorized/.test(r.message)) {

答案 1 :(得分:2)

只是做:

if (r.message.match(/approved/) || r.message.match(/authorized/)) {
  ...
}

答案 2 :(得分:0)

如果您使用.search()而不是.match(),请使用它来与数字进行比较。

- > example< -