-1

I have found plenty of questions that almost answer my question, for example this myString.replace( VARIABLE, "") ...... but globally but they all lack one detail.

I want to do something like this

var clipText = "aaabccc";
var replaceStr = "abc";
var withStr = "def";
clipText = clipText.replace(/replaceStr/g, withStr);

That is, use two variables as arguments to replace but replace seems to interpret the variable names literally rather than using their assigned value. I also want to replace all occurrences, hence the g after replaceStr.

What gives?

d-b
  • 695
  • 3
  • 14
  • 43

1 Answers1

1

You can try using RegExp constructor function:

var clipText = "aaabccc";
var replaceStr = "abc";
var withStr = "def";
var regex = new RegExp(replaceStr,"g");
clipText = clipText.replace(regex, withStr);
console.log(clipText);
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Do I *need* to use a regexp in my situation? I have no problems doing it but it seems just very ad-hoc that `replace` only accepts literal strings, not variables containing literal strings!?!? – d-b Apr 01 '20 at 14:14
  • @d-b, if you want to use variable then you have to use `new RegExp()`, though you can directly use the text like... `clipText.replace(/abc/g, withStr);`:) – Mamun Apr 01 '20 at 14:26
  • But abc in your example is not a variable? – d-b Apr 01 '20 at 14:30
  • @d-b, that is what I am trying to say, if you put the text (*abc*) in a variable then you have to use `new RegExp()`:) – Mamun Apr 01 '20 at 14:33
  • That is just weird. It deserves its own question. Does even Perl work like that (i.e., a string without quotations or similar is treated like a string rather than a variable)?? – d-b Apr 01 '20 at 16:17