3

I'm trying to replace some words (all the words present in my rootscope data array) for add a tooltip.

My code :

.directive('replaceDirective', function($rootScope, $compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function(scope, element, attrs) {

            //For exemple
            //$rootScope.data = ["word1", "word2", "word3", etc..]; 

            var test = {
                getTest: function(e, word) {
                    return RegExp(e.toString().replace(/\bxx\b/g, "").replace(/xx/g, word), "g")
                }
            };

            scope.$watch(attrs.replaceDirective, function(html) {
                for (var i=0; i<$rootScope.data.length; i++) {
                    var tooltipWord = $rootScope.data[i].word;
                    var tooltipDescription = $rootScope.data[i].def;
                    var template = '<a data-html="true" class="tooltip" title="' + tooltipDescription + '" data-toggle="tooltip" data-placement="top" tooltip>' + tooltipWord + '</a>';

                    var oldRegex = /\bxx\b/;
                    html = html.replace(test.getTest(oldRegex, tooltipWord), template);
                }

                element.html(html);
                $compile(element.contents())(scope);
            });
        }
    };
});

It doesn't work! I have an error.

The error is:

"Error: nothing to repeat  
   .link/test.getTest@file:www/js/directives.js:336:28  
   .link/<@file:www/js/directives.js:357:76"
Chéramy Alexandre
  • 412
  • 1
  • 7
  • 22
  • I saw a single double quotes here `html = html.replace(test.getTest(oldRegex, tooltipWord), template");` – Avinash Raj Jul 07 '15 at 07:29
  • Just look at the code highlighting in the code block in your question. Specifically, the last few lines. You have a stray `"` there that you'd have seen in any IDE with syntax highlighting. – Cerbrus Jul 07 '15 at 07:30
  • It just an copy/past error. I will edit my post! – Chéramy Alexandre Jul 07 '15 at 07:38
  • 2
    The problem is with forming the dynamic regex part. "Nothing to repeat" appears when you set the quantifier after another quantifier (e.g. `(text)*+`). Just make sure you [escape the metacharacters](http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) in your regex before testing. – Wiktor Stribiżew Jul 07 '15 at 07:49

1 Answers1

0

The problem is with forming the dynamic regex part. "Nothing to repeat" erro appears when you set the quantifier after another quantifier, anchor or alternation operator.

So, perhaps, your regex starts looking like (text)*+, or (a|?b), or *\s+.

To fix this, make sure you escape the metacharacters in your regex before testing.

function escapeRegExp(str) {
  return str.replace(/[\[\]\/{}()*+?.\\^$|-]/g, "\\$&");
}

And

getTest: function(e, word) {
 return RegExp(escapeRegExp(e.toString().replace(/\bxx\b/g, "").replace(/xx/g, word)), "g")
}
Community
  • 1
  • 1
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397