AngularJS,正则表达式导致测试出错
当用户输入特定表达式时,它将被转换为视图中的按钮 代码如下:AngularJS,正则表达式导致测试出错,angularjs,regex,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) {
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>'
}));
};
,我首先想到的是,我确实犯了一个拼写错误,所以我尝试了以下方法:
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>'
}));
没有出现错误,但没有制作按钮
然后,我试了一下:
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>'
}));
在看了这个之后,我相信,我必须以某种方式迭代我的文本,但我不知道如何在我的案例中这样做
有人能帮我更正代码,这样它也能在测试中工作吗
编辑:
当我这样做时:
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>'
}));
needle=/argumentation-link_to\(\d+)\s([\w\sÀ-ž]+)\/;
return$sce.trustAsHtml(haystack.replace)(针,功能(匹配){
返回“”+指针执行器(匹配)[2]+“”
}));
没有错误发生,但只生成第一个按钮。这是显而易见的,因为缺少全局标志
由于代码在测试之外工作,我认为问题更多的是标志而不是构造函数 我找到了一个便宜的修复程序,它不需要太多的维护工作:
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>'
}));
needle=/argumentation-link_to\(\d+)\s([\w\sÀ-ž]+)\)/gi
needle2=/argumentation-link_to\(\d+)\s([\w\sÀ-ž]+)\)/
return$sce.trustAsHtml(haystack.replace)(针,功能(匹配){
返回'+2.exec(匹配)[2]+''
}));
使用needle=“辩论链接到\\(\\d+),\\s([\\w\\sÀ-ž]+)\\”
@WiktorStribiżew这导致了这个错误:error:needle.exec不是一个函数,但我将研究您给我的stackoverflow问题