Code:
var csMasterPrefix = 'CS_',
cpMasterPrefix = 'CP_',
csContentPrefix = 'CSContent_',
cpContentPrefix = 'CPContent_';
/* ... */
$this.attr("id")
.replace(csMasterPrefix,'')
.repl开发者_高级运维ace(cpMasterPrefix,'')
.replace(csContentPrefix,'')
.replace(cpContentPrefix,'')
.replace('ibtn','')
.replace('btn','')
.replace('lbtn','')
.replace('img','')
.toLowerCase();
Question: Let me preface by saying I've looked at the solutions that say to make your own "clean" function. My question really isn't how to do that, but rather how can I make ONE regular expression that would combine all of the replace calls into one?
By using RegExp
, the choice operator |
and the global flag g
:
var to_replace = [csMasterPrefix, ..., 'ibtn', ...];
var id = $this.attr("id").replace(new RegExp(to_replace.join('|'), 'g'), '');
Don't know if it is the most efficient solution, but it will work.
Alternative you could loop over to_replace
and do normal string replacement.
精彩评论