Reputation: 382
I've a few predefined filter options on my page to filter my datatable. When clicking one, it gets added to the filter of the specific column. But I've a big problem with whitespaces... for example I've those options:
"old & good", "cheap & nice", "expensive"
All clicked options are stored in an array. For filtering I do
var term = array.join('|'); //--> term = "old & good|cheap & nice|expensive"
dataTable.fnFilter(term, column, true, true);
It works fine if there are no strings with whitespaces and "&" or only one. a solo "cheap & nice" is working, but "cheap & nice|expensive" doesn't... also "expensive|what|ever" works when there are no whitespaces.
How can I get the filter work?
--------edit----------
some further explanation:
My code imports data from (user-defined) csv and generates for the first column some buttons, one for every unique entry in this column. The user can click on the buttons to filter the table, only the clicked entrys should be displayed. The button gets the entry as value, like in this example.
<input type="button" value="cheap & nice" onclick="myFilterFunction(this)"/>
To know wich buttons have been clicked, their value gets stored in a normal array. My callback function for the click looks into this array, joins the names to one regexp and gives this string to the fnFilter(), like posted above.
This works fine as long as there is no entry with whitespaces in it. But i can't remove the whitespaces, because then the filter can't find the entry wich really has whitespaces in it.
Upvotes: 2
Views: 2186
Reputation: 61
You should quote special characters.
If this is constant string just use slash 'old /& good'
If this is user input you should use quote function. There is no such function by default in JS, but you can use http://phpjs.org/functions/preg_quote/
function preg_quote (str, delimiter) {
return (str + '').replace(new RegExp('[\&.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}
So if you have user input like:
var input = ["old & good","cheap & nice","expensive"];
var regexp_string = input.map(function(val){ return preg_quote(val,"/") }).join("|");
Upvotes: 1
Reputation: 382
Finally, after a lot of hours, I found a solution for my problem.
var array = ["old & good","cheap & nice","expensive"];
var regexp = array.join('|').replace("&", "\\&").replace(/\s/g, "\\s");
--> "old\s\&\sgood|cheap\s&\snice|expensive"
Giving this term to the fnFilter()
works!
But it would be nice to have a function, wich can convert all special characters to the corresponding regexp, in the style of @BoomyJee suggestion. If there is such a function, please let me know.
Upvotes: 3
Reputation: 23
You could use something like this to remove whitespace in javascript instead of regex:
s.replace(/\s+/g, ' ');
Or this
var str = " Hello World! ";
alert(str.trim());
Upvotes: 0