最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex .match() is null - Stack Overflow

programmeradmin8浏览0评论
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

Is this not the correct way to do matching in 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);
    }
},
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

Is this not the correct way to do matching in 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);
    }
},
Share Improve this question edited Feb 15, 2011 at 18:40 p.campbell 101k70 gold badges262 silver badges326 bronze badges asked Feb 15, 2011 at 18:30 BenBen 62.4k116 gold badges324 silver badges504 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17

Since you are getting authorized message the statement r.message.match(/approved/) will return null and hence the issue.

Rewrite the check as follows:

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

Just do:

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

Use .search() instead of .match() if you're using it in comparison to numbers.

--> example <--

发布评论

评论列表(0)

  1. 暂无评论