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??
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??
Share Improve this question asked Jun 26, 2009 at 13:32 Trevor BrambleTrevor Bramble 8,8136 gold badges32 silver badges29 bronze badges 1- possible duplicate of How do you pass a variable to a Regular Expression JavaScript? – fxp Commented Nov 6, 2013 at 7:46
1 Answer
Reset to default 21What you want is to use the RegExp object:
text = text.replace(new RegExp(replacement, 'g'), '');
Simple example of it in action.