【问题标题】:Regex.test is giving me an errorRegex.test 给我一个错误
【发布时间】:2015-12-22 13:19:37
【问题描述】:

我有以下 javascript...

$.post(url, data, function (json) {
        var patt = new RegExp('/^\[{"dID":/');
        if (patt.test(json)) {

            //output json results formatted
} else {

        //error so output json string
            $('#diaryTable').replaceWith(json);    

        }
    }, 'json');

基本上我的 json 应该是一个以

开头的有效 json

[{"dID":

否则就是

[{ 来自 try catch 异常的 ex.Message... }]

不幸的是,我收到错误 JavaScript 运行时错误:正则表达式中的预期']'

我在 RegEx101.com 上检查了我的 RegEx /^[{"dID":/ 以及一些测试数据,并且我的测试按预期工作。有什么想法吗?

【问题讨论】:

  • var patt = /^\[\{"dID":/;
  • 您需要转义[ 括号,否则它会充当正则表达式运算符。如果你想测试正则表达式,我发现regexr 是最好的网站。

标签: javascript json regex


【解决方案1】:

好的,感谢所有试图提供帮助的人...我认为我对问题的解释不太清楚...

我已经通过检查我是否有一个有效的对象来解决我的问题...一个有效的对象将有一个 dID 值,所以我使用了...

 if (typeof json[0].dID != 'undefined') {
            // valid object
            var out = "";
            var i;
            var a = "N"

            for (i = 0; i < json.length; i++) {

                out += '<div class="dOuter' + a + '">';
                out += '<div class="dInner">' + json[i].dDate + '</div>';
                out += '<div class="dInner">' + json[i].dRef + '</div>';
                out += '<div class="dInner">' + json[i].dTeam + '</div>';
                out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
                out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
                out += '<div class="dServer">' + json[i].dServer + '</div>';
                out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';

                if (a == "N") {
                    a = "A";
                } else {
                    a = "N";
                }
            }

            $('#diaryTable').replaceWith(out);
        }

        else { 
            //error so output json string
            $('#diaryTable').replaceWith(json);    
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2017-11-12
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多