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

For my website I use the dataTable plugin and to give the user the possibility to filter the results. I

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745643867a4637854.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信