Ben
Ben

Reputation: 62474

Javascript regex .match() is null

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);
    }
},

Upvotes: 8

Views: 12376

Answers (3)

Shaz
Shaz

Reputation: 15887

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

--> example <--

Upvotes: 0

Chandu
Chandu

Reputation: 82943

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)) {

Upvotes: 17

CanSpice
CanSpice

Reputation: 35828

Just do:

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

Upvotes: 2

Related Questions