AngularJS,正则表达式导致测试错误

时间:2017-01-12 21:27:12

标签: angularjs regex

当用户输入特定表达式时,它会转换为视图中的按钮。

以下是代码:

        scope.buttonmaker = function(haystack) {
            needle = /argumentation-link_to\((\d+),\s([\w\sÀ-ž]+)\)/;

            return $sce.trustAsHtml(haystack.replace(new RegExp(needle, 'gi'), function(match) {
                return '<button ng-click="goToArgumentation(' +  needle.exec(match)[1] + ', 2, 3, false)" class="btn btn-md btn-info"> ' + needle.exec(match)[2] + '</button>'
            }));
        };

代码可以正常工作,并且它还可以捕获多个与正则表达式匹配的表达式,并且按钮正确生成。

但是,运行测试时会发生以下错误:

Error: Cannot supply flags when constructing one RegExp from another.
RegExp@[native code]
buttonmaker@http://127.0.0.1:46071/assets/application-a2e90460a4bfb22fd82a11fde4c3041112d7349933767571c5e4928ad1951bdb.js:56321:68
fn

Looking at this stackoverflow-question,我首先想到的是,我确实犯了拼写错误,所以我尝试了这个:

needle = "argumentation-link_to\((\d+),\s([\w\sÀ-ž]+)\)";

没有错误发生,但按钮没有发生。

然后,我尝试了这个:

needle = /argumentation-link_to\((\d+),\s([\w\sÀ-ž]+)\)/gi

        return $sce.trustAsHtml(haystack.replace(needle, function(match) {
            return '<button ng-click="goToArgumentation(' +  needle.exec(match)[1] + ', 2, 3, false)" class="btn btn-md btn-info"> ' + needle.exec(match)[2] + '</button>'
        }));

发生此错误:

Error: needle.exec(...) is null

看完这个stackoverflow-question后,我相信,我必须以某种方式重复我的文字,但我不知道如何在我的案例中做到这一点。

有人可以帮我修改代码,所以它也可以在测试中使用吗?

编辑:

当我这样做时:

needle = /argumentation-link_to\((\d+),\s([\w\sÀ-ž]+)\)/;

   return $sce.trustAsHtml(haystack.replace(needle, function(match) {
        return '<button ng-click="goToArgumentation(' +  needle.exec(match)[1] + ', 2, 3, false)" class="btn btn-md btn-info"> ' + needle.exec(match)[2] + '</button>'
    }));

没有错误发生,但只有第一个按钮出现。这很明显,因为缺少全局标志。

由于代码在测试之外工作,我认为,问题更多的是关于标志而不是构造函数。

1 个答案:

答案 0 :(得分:0)

我找到了一个便宜的修复程序,它不需要太多的维护工作:

needle = /argumentation-link_to\((\d+),\s([\w\sÀ-ž]+)\)/gi
needle2 = /argumentation-link_to\((\d+),\s([\w\sÀ-ž]+)\)/

    return $sce.trustAsHtml(haystack.replace(needle, function(match) {
        return '<button ng-click="goToArgumentation(' +  needle2.exec(match)[1] + ', 2, 3, false)" class="btn btn-md btn-info"> ' + needle2.exec(match)[2] + '</button>'
    }));