Activity › Forums › Salesforce® Discussions › How can we use regex for searching in datatable in Salesforce?
Tagged: Apex DataTable, API, Datatable Component, Global Search, REGEX
-
How can we use regex for searching in datatable in Salesforce?
Posted by Anjali on August 22, 2018 at 1:04 PMHow can we use regex for searching in datatable in Salesforce?
shariq replied 7 years, 7 months ago 4 Members · 3 Replies -
3 Replies
-
Hi Anjali,
Searching a table is one of the most common user interactions with a DataTables table, and DataTables provides a number of methods for you to control this interaction. There are APIs for the global search (search()) and for each individual column (column().search()).
Below is the example:
$(‘#example’).DataTable().search(
$(‘#global_filter’).val(),
$(‘#global_regex’).prop(‘checked’),
$(‘#global_smart’).prop(‘checked’)
).draw();Hope this helps.
- [adinserter block='9']
-
hi
Try this code snippet:
As an alternative approach you could try to use a custom filter :
$(‘#search-inp’).keyup(function() {
var str,
term = $(this).val(),
regexp = new RegExp(‘\\b’ + term + ‘\\b’, ‘ig’);removeHighlight();
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex ) {
str = data[1];
return regexp.test(str) ? true : false;
}
);
table.draw();
highlight(term);
$.fn.dataTable.ext.search.pop();
})Thanks
-
Hi,
Try this –
<aura:application extends=”force:slds”>
<aura:attribute name=”data” type=”List” />
<aura:attribute name=”columns” type=”List” />
<aura:attribute name=”filteredData” type=”List” />
<aura:attribute name=”filter” type=”String” /><aura:handler name=”init” value=”{!this}” action=”{!c.init}” />
<lightning:input type=”text” onchange=”{!c.filter}” value=”{!v.filter}” label=”Filter” />
<lightning:datatable keyField=”name” columns=”{!v.columns}” data=”{!v.filteredData}” />
</aura:application>Controller –
({
init: function(component, event, helper) {
var sample = [];
// Create 10 random people
[…Array(10).keys()].forEach(v=>sample.push({name:”Person “+(v+1), age: Math.floor(Math.random()*80)}));
// initialize data
component.set(“v.columns”, [{type:”text”,label:”Name”,fieldName:”name”},{type:”number”,label:”Age”,fieldName:”age”}]);
component.set(“v.data”, sample);
component.set(“v.filteredData”, sample);
},
filter: function(component, event, helper) {
var data = component.get(“v.data”),
term = component.get(“v.filter”),
results = data, regex;
try {
regex = new RegExp(term, “i”);
// filter checks each row, constructs new array where function returns true
results = data.filter(row=>regex.test(row.name) || regex.test(row.age.toString()));
} catch(e) {
// invalid regex, use full list
}
component.set(“v.filteredData”, results);
}
})Hope this helps.
Log In to reply.