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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5007865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:38:26  来源:igfitidea点击:

Javascript regex .match() is null

javascriptregex

提问by Webnet

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?

这不是在 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);
    }
},

回答by Chandu

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

由于您获得了授权消息r.message.match(/approved/),因此该语句将返回 null,从而导致问题。

Rewrite the check as follows:

将支票改写如下:

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

回答by CanSpice

Just do:

做就是了:

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

回答by Shaz

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

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

--> example<--

-->例子<--