最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to escape special characters in regular expressions - Stack Overflow

programmeradmin7浏览0评论

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.

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

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:

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.

Can anyone help me please?

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.

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

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:

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.

Can anyone help me please?

Share Improve this question edited Sep 30, 2015 at 13:21 Gyrocode. 59k16 gold badges157 silver badges192 bronze badges asked Sep 29, 2015 at 14:34 user2550641user2550641 3474 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

SOLUTION

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

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.

发布评论

评论列表(0)

  1. 暂无评论