I am trying to use variables in a regular expression, in JavaScript.
Consider this function that will extract all the text between <b>
and </b>
tags in a given string
function Tags_Content_B(html)
{
return html.match(/<b>(.*?)<\/b>/g).map(function(val){return val.replace(/<\/?b>/g,'');});
}
To make the function more generic, I would like to add a second parameter: the tag I want to extract content from. Following other examples on how to use variables in regex, I tried this
function Tags_Content(html, tag)
{
var match_exp = new RegExp("/<" + tag + ">(.*?)<\/" + tag + ">/g");
var replace_exp = new RegExp("/<\/?" + tag +">/g");
return html.match(match_exp).map(function(val){return val.replace(replace_exp,'');});
}
However it doesn't work, no matches, no replacements. Any hint on what am I doing wrong?