admin管理员组

文章数量:1434916

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.

本文标签: javascriptHow to escape special characters in regular expressionsStack Overflow