-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?

resle
  • 2,254
  • 4
  • 19
  • 37
  • 2
    Please don't use regular expressions to parse HTML... use an industry-standard parser that has actual security measures to prevent XSS attacks. – Patrick Roberts Jun 03 '17 at 05:02
  • This is just a personal, "hobby" project with zero exposure to external and/or professional use – resle Jun 03 '17 at 05:07
  • Did you read [the documentation about `RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)? Have a look at the examples. – Felix Kling Jun 03 '17 at 05:10
  • Did you proof-read your post? Tags such as `` must be delimited by backticks or else they will disappear. –  Jun 03 '17 at 05: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? –  Jun 03 '17 at 05:13
  • @torazaburo thanks. Mistake corrected, RegExp object usage learned. – resle Jun 03 '17 at 05:16

1 Answers1

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"));
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153