Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  178] [ 7]  / answers: 1 / hits: 21761  / 13 Years ago, fri, august 5, 2011, 12:00:00

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

})

More From » jquery

 Answers
13

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

});

[#90790] Thursday, August 4, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
;