Regex to exclude keywords

Regex to exclude keywords

westowlwestowl Posts: 3Questions: 1Answers: 0
edited August 2017 in Free community support

Hi everyone,

Very new to Javascript and DataTables. I've managed to set up everything except this one last piece. I have a long string in each cell (a paragraph, let's say) and I want to create a filter that will return any rows containing "plant" but not if there's a specific modifier ("yellow plant" or "purple plant").

This is because in my filters I want to have options for "yellow plant", "plant" and "purple plant" where the middle "plant" is a standard color associated with plants. So if a user chooses "plant" I would want to exclude "yellow plant" and "purple plant". Hope this makes sense... I've tried regex editors but have failed so far.

$('.filter').change(function() {
    var checked = this.checked ? true : false;
    var keyword = $(this).attr("value");
    var datacol = $(this).attr("data-col");

    //exclude yellow and purple plants if filter value is simply "plant"
    /* if(keyword=='plant') {
        keyword = ''; //regex here?
    }*/

    table.column(datacol).search(keyword,true,false).draw(); 
});

Thanks so much in advance.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,309Questions: 26Answers: 4,947

    This regex may work:
    ^(?!.*(purple|yellow)\Wplant).*$

    It uses negative look ahead.

    You can test it out here:
    https://regex101.com/

    You can paste in your paragraphs to see if it works as desired.

    Kevin

  • westowlwestowl Posts: 3Questions: 1Answers: 0

    Thanks so much @kthorngren ! This gets me halfway there... no more yellow or purple plants! But I'm also getting rows without the word "plant" at all.

  • kthorngrenkthorngren Posts: 21,309Questions: 26Answers: 4,947
    Answer ✓

    I'm also getting rows without the word "plant" at all.

    Didn't test for that case. I made a couple changes and put them in this test case:
    http://live.datatables.net/nuwumeji/1/edit

    You can add rows to test other scenarios.

    Kevin

  • westowlwestowl Posts: 3Questions: 1Answers: 0

    Kevin, thank you so much! It worked! I'm going to have to study regex more, starting with what you shared with me... but maybe next time I can help someone like you helped me. Thanks again!

  • kthorngrenkthorngren Posts: 21,309Questions: 26Answers: 4,947

    but maybe next time I can help someone like you helped me

    Be careful, it becomes addictive :smile:

    Kevin

This discussion has been closed.