Javascript AngularJS:Regex无重复错误
我正在尝试替换一些单词(我的rootscope数据数组中的所有单词)以添加工具提示 我的代码:Javascript AngularJS:Regex无重复错误,javascript,regex,angularjs,angularjs-directive,Javascript,Regex,Angularjs,Angularjs Directive,我正在尝试替换一些单词(我的rootscope数据数组中的所有单词)以添加工具提示 我的代码: .directive('replaceDirective', function($rootScope, $compile) { return { restrict: 'A', replace: true, link: function(scope, element, attrs) { //For exemple
.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);
});
}
};
});
.directive('replaceDirective',函数($rootScope,$compile){
返回{
限制:“A”,
替换:正确,
链接:函数(范围、元素、属性){
//例如
//$rootScope.data=[“word1”、“word2”、“word3”等];
var测试={
getTest:函数(e,word){
返回RegExp(例如toString().replace(/\bxx\b/g,“”)。replace(/xx/g,word),“g”)
}
};
作用域$watch(attrs.replaceDirective,函数(html){
对于(var i=0;i而言,问题在于形成动态正则表达式部分。当您将量词设置在另一个量词、锚定或交替运算符之后时,会出现“无需重复”错误
因此,您的正则表达式可能开始看起来像(text)*+
,或(a |?b)
,或*\s+
要解决此问题,请确保在测试之前输入正则表达式
function escapeRegExp(str) {
return str.replace(/[\[\]\/{}()*+?.\\^$|-]/g, "\\$&");
}
及
我在这里看到了一个双引号html=html.replace(test.getTest(oldRegex,tooltipWord),template”);
只要看看问题代码块中突出显示的代码。特别是最后几行。你有一个错误的“
在任何IDE中都会看到语法突出显示。这只是一个复制/过去的错误。我将编辑我的帖子!问题在于如何形成动态正则表达式部分。当您在另一个量词(例如(text)*+
)之后设置量词时,“无需重复”。只需确保在测试之前输入正则表达式即可。
function escapeRegExp(str) {
return str.replace(/[\[\]\/{}()*+?.\\^$|-]/g, "\\$&");
}
getTest: function(e, word) {
return RegExp(escapeRegExp(e.toString().replace(/\bxx\b/g, "").replace(/xx/g, word)), "g")
}