Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript's replace() method with global switch on a variable

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??

like image 765
Trevor Bramble Avatar asked Jun 26 '09 13:06

Trevor Bramble


1 Answers

What you want is to use the RegExp object:

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

Simple example of it in action.

like image 78
cgp Avatar answered Nov 05 '22 08:11

cgp