Javascript.replace () with multiple calls, some with variables, some with plain text

The code:

var csMasterPrefix = 'CS_',
    cpMasterPrefix = 'CP_',
    csContentPrefix = 'CSContent_',
    cpContentPrefix = 'CPContent_';

/* ... */

$this.attr("id")
    .replace(csMasterPrefix,'')
    .replace(cpMasterPrefix,'')
    .replace(csContentPrefix,'')
    .replace(cpContentPrefix,'')
    .replace('ibtn','')
    .replace('btn','')
    .replace('lbtn','')
    .replace('img','')
    .toLowerCase();

Question: Let me introduce the preface by saying that I looked at the solutions that say to make your own β€œpure” function. My question really is not how to do this, but how can I make an ONE regex that combines all replacement calls into one?

+3
source share
1 answer

Using , the select operator and the global flag : RegExp|g

var to_replace = [csMasterPrefix, ..., 'ibtn', ...];
var id = $this.attr("id").replace(new RegExp(to_replace.join('|'), 'g'), '');

I do not know if this is the most effective solution, but it will work.

, to_replace .

+8

All Articles