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.

2
  • stackoverflow.com/questions/13683606/… Commented Apr 26, 2017 at 8:42
  • 1
    prasad's answer answered my question far clearer than either of the linked questions that I am an apparent duplicate of. Commented Apr 26, 2017 at 8:48

1 Answer 1

1

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

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

myVar = myVar.replace(new RegExp(myString, 'g'), '');
console.log(myVar)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.