When a button is clicked, it's data-marker attribute is added to (or removed from) the array markers.
So for example if I've clicked all three of the buttons - Apples, Oranges and Pears, the markers array will read [Apples,Oranges,Pears]. This is working fine.
I then want to do a new regex for each object in the array, but I don't know how.
Currently when I call the regex it just does the whole array as a string, and the resulting regex looks like this:
/Apples,Oranges,Pears/gi
But I want it to do a new regex for each object in the array, like this:
/Apples/gi
/Oranges/gi
/Pears/gi
How can I do this? Working snippet of what I have so far below:
// Create new array to store data-marker values
var markers = [];
// Declare global variable for use later
var qsRegexx;
// When user clicks any button having class 'z-btn-i'...
var $quickfilter = $('.z-btn-i').click(function() {
// Store some more variables
var $this = $(this);
var datamarker = $this.attr('data-marker');
// Add or remove the value of the button's data-marker attribute to/from the array 'markers'
if (markers.indexOf(datamarker)!=-1) {
markers.splice(markers.indexOf(datamarker),1);
} else {
markers.push(datamarker);
}
console.log(markers);
console.log(qsRegexx);
// THIS IS WHERE I'M STUCK
// I want to do a new regex for each object in the array 'markers', not one regex of all of them together...
qsRegexx = new RegExp(markers, 'gi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="z-btn-i" data-marker="Apples">Apples</button>
<button class="z-btn-i" data-marker="Pears">Pears</button>
<button class="z-btn-i" data-marker="Oranges">Oranges</button>