2

I have a complicated regEx inside a string replace and I want to use a variable called "tagname" instead of the word Category, but I don't know how to do this.

$("textarea").val().replace(/\<Category\>(.*)\<\/Category\>/gi, "<Category>TextVariable</Category>");

I have tried something like this, but it didn't work in the first parameter.

$("textarea").val().replace("/\<" + tagname + "\>(.*)\<\/" + tagname "\>/gi", "<" + tagname + ">" + TextVariable + "</" + tagname + ">");
Guest
  • 207
  • 2
  • 3
  • 7

2 Answers2

6

You can use the RegExp constructor with a string pattern and flags:

var regex = new RegExp("<" + tagname + ">(.*)</" + tagname + ">", "gi");
$("textarea").val().replace(regex, "<" + tagname + ">" + TextVariable + "</" + tagname + ">");
Tim Down
  • 318,141
  • 75
  • 454
  • 536
6

Use the RegExp constructor instead of regex literal.

var regex = new RegExp("<" + tagname + ">(.*)</" + tagname + ">", "gi");
$("textarea").val().replace(regex, "<" + tagname + ">" + 
   textVariable + "</" + tagname + ">");

you can simplify it as:

//capture the tag name:
var regex = new RegExp("<(" + tagname + ")>(.*)</" + tagname + ">", "gi");
$("textarea").val().replace(regex, "<$1>" + textVariable + "</$1>");

But bear in mind that parsing xml/html with regex is a baaad idea

Community
  • 1
  • 1
Amarghosh
  • 58,710
  • 11
  • 92
  • 121