我有以下使用大量正则表达式的 javascript 函数。有没有办法可以简化这个?
function encode(str){
if(typeof str==='number'){
return str;
}
if(typeof str!=='string'){
return '';
}
var enc=str;
enc=enc.replace(/_/g,'_u'); //underscore
enc=enc.replace(/(\r\n|\r|\n)/g,'_r'); //return
enc=enc.replace(/&/g,'_a'); //ampersand
enc=enc.replace(/\\/g,'_b'); //backslash
enc=enc.replace(/:/g,'_c'); //colon
enc=enc.replace(/"/g,'_d'); //double quote
enc=enc.replace(/=/g,'_e'); //equals
enc=enc.replace(/€/g,'_4'); //euro
enc=enc.replace(/\>/g,'_g'); //greater than
enc=enc.replace(/#/g,'_h'); //hash
enc=enc.replace(/'/g,'_i'); //inverted comma
enc=enc.replace(/\</g,'_l'); //less than
enc=enc.replace(/¬/g,'_n'); //not
enc=enc.replace(/\|/g,'_1'); //pipe
enc=enc.replace(/¦/g,'_2'); //broken pipe
enc=enc.replace(/\+/g,'_p'); //plus
enc=enc.replace(/£/g,'_3'); //pound
enc=enc.replace(/\?/g,'_q'); //question mark
enc=enc.replace(/\//g,'_s'); //slash
enc=enc.replace(/\~/g,'_t'); //tlide
enc=enc.replace(/\`/g,'_z'); //back quote
enc=enc.replace(/\s/g,'_0'); //space
enc=enc.replace(/[\u0000-\u001f]/g,'');
return enc;
};