-3

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?

6
  • 2
    Please don't use regular expressions to parse HTML... use an industry-standard parser that has actual security measures to prevent XSS attacks. Commented Jun 3, 2017 at 5:02
  • This is just a personal, "hobby" project with zero exposure to external and/or professional use Commented Jun 3, 2017 at 5:07
  • Did you read the documentation about RegExp? Have a look at the examples. Commented Jun 3, 2017 at 5:10
  • Did you proof-read your post? Tags such as <b> must be delimited by backticks or else they will disappear. Commented Jun 3, 2017 at 5:10
  • 3
    As the documentation states clearly, when using the RegExp constructor, do not include beginning and ending / characters, and specify the flags (g) as a second parameter. Nor can the parameter to replace be a regexp itself--what would that mean? Commented Jun 3, 2017 at 5:13

1 Answer 1

3

With the understanding that you should never actually do 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(value) {
    return value.replace(replace_exp, '');
  });
}

console.log(Tags_Content("Let's <b>test</b> the <code>b</code> tag <b>people!</b>", "b"));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.