1

I'm attempting to replace all instances of a string within a variable, but the string I'm looking for is also a variable. How can I add this string within a regex?

var myVar = HelloWorldHello;
var myString = Hello;

myVar = myVar.replace(/\\' + myString + '/g, '');

The above doesn't seem to be working. I need to end up with World.

mpdc
  • 3,550
  • 5
  • 25
  • 48
  • http://stackoverflow.com/questions/13683606/replace-all-instances-in-string-with-a-variable-as-the-search-javascript – Mohamed-Yousef Apr 26 '17 at 08:42
  • 1
    prasad's answer answered my question far clearer than either of the linked questions that I am an apparent duplicate of. – mpdc Apr 26 '17 at 08:48

1 Answers1

1

use with new RegExp('string', 'g')

var myVar = 'HelloWorldHello';
var myString = 'Hello';

myVar = myVar.replace(new RegExp(myString, 'g'), '');
console.log(myVar)
prasanth
  • 22,145
  • 4
  • 29
  • 53