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

12,215

What you want is to use the RegExp object:

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

Simple example of it in action.

Share:
12,215
Trevor Bramble
Author by

Trevor Bramble

Updated on June 11, 2022

Comments

  • Trevor Bramble
    Trevor Bramble almost 2 years

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

  • Vincent Robert
    Vincent Robert almost 15 years
    Don't forget to escape regexp special chars with backslashes