0

When the user enters a specific expression, it gets translated to a button in the view.

Here is the code:

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

The code works, as it should and it also captures more than one expression, that match the Regex and the buttons are made correctly.

However, when running a test, this error happens:

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, I first thought, that I did make a spelling mistake, so I tried this:

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

No errors occur, but the buttons weren't made.

Then, I tried this:

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

This error occurs:

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

After looking at this stackoverflow-question, I believe, I have to somehow iterate over my text, but I don't know how to do it in my case.

Can someone help me to correct the code, so it does work in tests too?

EDIT:

When I do this:

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

No errors occur, but ONLY the first button gets made. This is obvious, because the global flag is missing.

And since the code works outside of tests, I think, the problem is more about the flags than the constructor.

Community
  • 1
  • 1
Metaphysiker
  • 983
  • 2
  • 18
  • 35

1 Answers1

0

I found a cheap fix, which requires not too much maintenance-work:

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>'
    }));
Metaphysiker
  • 983
  • 2
  • 18
  • 35