7

I can't any example of this after being unable to puzzle out how it would work on my own.

All I want to do is take a string which has been assigned to a value, and use that as the replace match string for all matches.

var replacement = 'i';
var text = 'tieiam';

text = text.replace(replacement, '');  // 'teiam'

text = text.replace(/tieiam/g, ''); // 'team'

How do I use them together??

1

1 Answer 1

21

What you want is to use the RegExp object:

text = text.replace(new RegExp(replacement, 'g'), '');

Simple example of it in action.

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

1 Comment

Don't forget to escape regexp special chars with backslashes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.