Using RegExp to dynamically create a Regular Expression, and filter content

21,278

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');
        }
    });

});
Share:
21,278
Mild Fuzz
Author by

Mild Fuzz

Updated on February 18, 2020

Comments

  • Mild Fuzz
    Mild Fuzz about 4 years

    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');
                        }
            });
    
        })
    
  • Phrogz
    Phrogz over 12 years
    More accurately, the / denote a regex literal but are not part of it, like " denotes a string literal, but is not part of the string.
  • Jan
    Jan about 5 years
    Don't forget when the regular expression uses \ slashes, to escape those to \\