Regex to exclude keywords
Regex to exclude keywords
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
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
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.
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
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!
Be careful, it becomes addictive
Kevin