james emanon
james emanon

Reputation: 11827

Why doesn't this regex work when mapping to hash?

Curious why this doesn't work. I have went thru many different permutations, but overall this is what I am trying to do and can't get it to work.

Basically, use the hash key to find match, then use that key to get the value with the hash reference.

 var arr = {'blah':'WULLVERT','misc':'DUDETTER'};
 var test_string = "maryLou is misc &&& such a cool mary blah dude yeah wullvert";
 test_string = test_string.replace(/(jQuery.map(reg,function(k,v){return v}).join("|"))/gi,arr["$1"]);
 test_string;

of course, when I use string literals.. this works: (though still can't use the $1 for the hash reference).

     test_string = test_string.replace(/(blah|msic)/gi,"$1_proofofconcept");

Upvotes: 1

Views: 286

Answers (1)

falsetru
falsetru

Reputation: 369394

Use new RegExp(..) to dynamically generate regular expression object.

var arr = {'blah':'WULLVERT','misc':'DUDETTER'};
var test_string = "maryLou is misc &&& such a cool mary blah dude yeah wullvert";
test_string.replace(
    new RegExp(jQuery.map(arr,function(v,k){return k}).join("|"), 'gi'),
    function(x) { return arr[x]; }
);
// => "maryLou is DUDETTER &&& such a cool mary WULLVERT dude yeah wullvert"

Upvotes: 2

Related Questions