Using the replace () JavaScript Method with Global Variable Switching

I can not give a single example of this because I could not figure out how it will work on its own.

All I want to do is take the string that was assigned to the value and use this as the match string for all matches.

var replacement = 'i'; var text = 'tieiam'; text = text.replace(replacement, ''); // 'teiam' text = text.replace(/tieiam/g, ''); // 'team' 

How to use them together?

+7
javascript replace global
source share
1 answer

You want to use the RegExp object:

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

A simple example of this in action.

+20
source share

All Articles