I am struggling with using the RegExp
object to allow me to dynamically create an expression, and apply it to a group of elements.
Here is a jsFiddle, below is the code:
<div id='selectors'><span>A-F</span><span>G-L</span><span>M-S</span><span>T-Z</span></div>
<a hreh=#>Astring</a>
<a hreh=#>Cstring</a>
<a hreh=#>Xstring</a>
<a hreh=#>Dstring</a>
<a hreh=#>Zstring</a>
$('div#selectors span').click(function(){
expression = "/^["+$(this).html()+"].*$/";
rx = RegExp(expression,'i');
console.log(rx,'expression');
$("a").each(function(){
if($(this).html().match(rx) !== null){
$(this).addClass('selected');
}
});
})
To use dynamic variable string as regex pattern in JavaScript, we can use the RegExp constructor. const stringToGoIntoTheRegex = "abc"; const regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g"); to create a regex object by calling the RegExp constructor with the "#" + stringToGoIntoTheRegex + "#" string.
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String. raw will prevent javascript from escaping any character within your string values.
$ means "Match the end of the string" (the position after the last character in the string).
[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.
JavaScript automatically adds "/" at the end and the beginning of the expression. Remove them from your string, Example Here
$('div#selectors span').click(function () { var expression = "^[" + $(this).html() + "].*$"; var rx = new RegExp(expression, 'i'); console.log(rx, 'expression'); $("a").each(function () { if ($(this).html().match(rx) !== null) { $(this).addClass('selected'); } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With