如何在正则表达式中转义特殊字符

时间:2021-10-12 00:27:09

For my website I use the dataTable plugin and to give the user the possibility to filter the results. I implemented some filter, which are dynamically loaded from the results and contains the all different values of each column.

对于我的网站,我使用dataTable插件,并为用户提供过滤结果的可能性。我实现了一些过滤器,它们从结果中动态加载,并包含每列的所有不同值。

As more than one filter can be combined, I deactived the smart search and had to active the regEx-search instead. All these things are working fine.

由于可以组合多个过滤器,因此我拒绝了智能搜索并且必须激活regEx-search。所有这些都很好。

My Problem is: I have content like "content (another content)", and for those contents containing brackets, the search doesn't work (no result is found).

我的问题是:我有“内容(另一个内容)”的内容,对于那些包含括号的内容,搜索不起作用(没有找到结果)。

Is there a possibility to mask the searchString before calling:

是否有可能在调用之前屏蔽searchString:

table.column('myColumn:name').search(searchString, true, false, true).draw();

I tried to replace the string with "\)" or something like this, but that doesn't help. If I just delete those special characters the results can't be found either as regEx search needs exact strings.

我试图用“\”“或类似的东西替换字符串,但这没有帮助。如果我只删除那些特殊字符,则无法找到结果,因为regEx搜索需要完全字符串。

Can anyone help me please?

有人可以帮我吗?

1 个解决方案

#1


2  

SOLUTION

You can add and use a function escapeRegExp() that will escape special characters as found in MDN - Regular Expressions article:

您可以添加和使用函数escapeRegExp(),它将转义MDN中的特殊字符 - 正则表达式文章:

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

// ... skipped ...

table.column('myColumn:name').search(escapeRegExp(searchString), true, false, true).draw();

DEMO

See this jsFiddle for code and demonstration.

有关代码和演示,请参阅此jsFiddle。

#1


2  

SOLUTION

You can add and use a function escapeRegExp() that will escape special characters as found in MDN - Regular Expressions article:

您可以添加和使用函数escapeRegExp(),它将转义MDN中的特殊字符 - 正则表达式文章:

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

// ... skipped ...

table.column('myColumn:name').search(escapeRegExp(searchString), true, false, true).draw();

DEMO

See this jsFiddle for code and demonstration.

有关代码和演示,请参阅此jsFiddle。