Activity Forums Salesforce® Discussions How can we use regex for searching in datatable in Salesforce?

  • madhulika shah

    Member
    August 22, 2018 at 1:26 pm

    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.

  • Parul

    Member
    September 21, 2018 at 1:36 pm

    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

  • shariq

    Member
    September 22, 2018 at 2:56 am

    Hi,

    Try this -

    <aura:application extends="force:slds">
    <!-- backing data -->
    <aura:attribute name="data" type="List" />

    <!-- data table attributes -->
    <aura:attribute name="columns" type="List" />
    <aura:attribute name="filteredData" type="List" />

    <!-- filter input -->
    <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.

Popular Salesforce Blogs

Popular Salesforce Videos