Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

    })
like image 978
Mild Fuzz Avatar asked Aug 05 '11 19:08

Mild Fuzz


People also ask

How do I create a dynamic expression in regex?

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.

Which of the following options can you use to create a dynamic RegExp using the string in a variable variable?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What's the difference between () and [] in regular expression?

[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.


1 Answers

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');         }     });  }); 
like image 58
Madara's Ghost Avatar answered Oct 07 '22 23:10

Madara's Ghost