开发者

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜