开发者

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

开发者 https://www.devze.com 2023-03-04 05:49 出处:网络
Code: var csMasterPrefix = \'CS_\', cpMasterPrefix = \'CP_\', csContentPrefix = \'CSContent_\', cpContentPrefix = \'CPContent_\';

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

精彩评论

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