When I store multiple regular expressions inside an array (so that I can manipulate the array later), it seems that .match() does not recognise them.
I've tested with a single expression (not an array) and this is fine, but when I try and match multiple expressions in an array, I don't get a result.
Please see below snippet with comments for a demonstration.
$(function() {
// Set global variable to call later
var regexMarkers;
// New array in which we store our regular expressions
var markers = [];
// When button is clicked...
$('.z-btn-i').click(function() {
// Declare some variables
var $this = $(this);
var me = $this.attr('data-marker');
// Make it clear that this regex is in the array now
$this.toggleClass('bold');
// Add/remove regular expressions from array
if (markers.indexOf(me)!=-1) {
markers.splice(markers.indexOf(me),1);
} else {
markers.push(me);
}
// This works (just a single regular expression) but I want it to work with multiple regexps
// regexMarkers = new RegExp(markers, 'gi');
// So here's me trying multiple regexps (an array of regular expressions) - but this code doesn't work
regexMarkers = markers.map(m => new RegExp(m, 'gi'));
// Click all three buttons and you can see that the multiple regexps are showing individually inside the array
console.log(regexMarkers);
});
// Debugging to see if .matches() works with the array (it doesn't - whereas with the single expression it does.
$('.z-btn-i').click(function() {
// If regexmarkers works, then match any text with it. if not, return 'true'.
var zuluResult = regexMarkers ? $('.text').text().match(regexMarkers) : true;
// Unfortunately it doesn't run and you'll see 'true' returned. So why is this?
console.log(zuluResult);
});
});
.bold {
font-weight: 900;
}
.red {
color: red;
}
<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>
<br>
<br>
<p class="text">I like Apples, but I don't like Pears or Oranges.</p>
How would I be able to get the .match() method to recognise each individual regex in my array?
.match()function? You didn't use Regex in your example. You can use.indexOf()function for simplicity.