1

我正在使用 Angular ui-utils 高亮过滤器,并且我有以下代码:

<span data-ng-bind-html="organization.level1Name | highlight:vm.search"></span>

当我使用 [ 或 ( 之类的特殊字符进行搜索时,会出现角度异常和应用程序中断。

SyntaxError:无效的正则表达式:/(/:在 v 处的新 RegExp(本机)处的未终止组。(http://localhost:50463/EIA/source/dist/vendor.min.js:72:1157)在 i 处(http ://localhost:50463/EIA/source/dist/vendor.min.js:38:92754 ) 在 cr.| ( http://localhost:50463/EIA/source/dist/vendor.min.js:38: 86832 ) 在 h.constant ( http://localhost:50463/EIA/source/dist/vendor.min.js:38:92126 ) 在 Object.e ( http://localhost:50463/EIA/source/dist/ vendor.min.js:38:101832 ) 在 v.$digest ( http://localhost:50463/EIA/source/dist/vendor.min.js:38:57280 ) 在 v.$apply ( http://本地主机:50463/EIA/source/dist/vendor.min.js:38:58986)在http://localhost:50463/EIA/source/dist/client.js:1007:31http://localhost:50463/EIA/source/dist/vendor.min.js:38:64888未定义

我尝试使用 ng-sanitize 库,但仍然遇到相同的错误。

请问,我该如何解决?

4

1 回答 1

1

您应该转义您的 RegExp输入,因为(它是正则表达式的特殊字符:

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

然后,只需使用它:

new RegExp(escapeRegExp(search), 'gi')
于 2015-04-10T11:52:01.583 回答