1

I'm trying too use JavaScripts "replace"-function to put tags around text given in between certain characters. Example:

str.replace(/\_(.*?)\_/gi, '<u>$1</u>');

Now this works fine but I want the "_"-characters to be given as a variable. For example:

var und = "_";
str.replace(/\und(.*?)\und/gi, '<u>$1</u>');

My question is how can I do that?

Thnx in advance!

2 Answers2

1

You will need to use RegExp constructor to construct a regex from variable:

var und = "_";
var re = new RegExp(und + '(.*?)' + und, "gi");

var repl = str.replace(re, '<u>$1</u>');
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You want to use new RegExp(pattern, flags) to build the regular expression from a string.

epascarello
  • 204,599
  • 20
  • 195
  • 236