Give certain character(s) as variables in JavaScripts "replace"-function

时间:2015-07-08 15:48:49

标签: javascript regex variables replace

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 个答案:

答案 0 :(得分: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>');

答案 1 :(得分:0)

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