AngularJS: Regex does not repeat anything error
I am trying to replace some words (all words represented in my root vegetable dataset) to 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);
});
}
};
});
This does not work! I have a mistake.
Mistake:
"Error: nothing to repeat
.link/test.getTest@file:www/js/directives.js:336:28
.link/<@file:www/js/directives.js:357:76"
+3
source to share
1 answer
The problem is in the formation of the dynamic part of the regular expression. The "repeat nothing" erro appears when you set a quantifier after another quantifier, bind operator, or alternation.
So, perhaps your regex is starting to look like (text)*+
, or (a|?b)
, or *\s+
.
To fix this, make sure you avoid 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")
}
0
source to share