你写了这段代码:
accentsTidy = function(s){ var r=s.toLowerCase(); r = r.replace(new RegExp("\\s",'g'),""); r = r.replace(new RegExp("[àáâãäå]","a"); r = r.replace(new RegExp("æ","ae"); r = r.replace(new RegExp("ç","c"); r = r.replace(new RegExp("[èéêë]","e"); r = r.replace(new RegExp("[ìíîï]","i"); r = r.replace(new RegExp("ñ","n"); r = r.replace(new RegExp("[òóôõö]","o"); r = r.replace(new RegExp("œ","oe"); r = r.replace(new RegExp("[ùúûü]","u"); r = r.replace(new RegExp("[ýÿ]","y"); r = r.replace(new RegExp("\\W",""); return r; };
我想如果回答我的问题,请.
如果我想要大字符(例如:ÁÉ – > A E等),那么我必须更改代码.
非常感谢你!
解决方法
你可以这样做:
accentsTidy = function(s) { var map = [ ["\\s",""],["[àáâãäå]","a"],["æ","ae"],["ç","c"],["[èéêë]","e"],["[ìíîï]","i"],["ñ","n"],["[òóôõö]","o"],["œ","oe"],["[ùúûü]","u"],["[ýÿ]","y"],["\\W",""] ]; for (var i=0; i<map.length; ++i) { s = s.replace(new RegExp(map[i][0],"gi"),function(match) { if (match.toUpperCase() === match) { return map[i][1].toUpperCase(); } else { return map[i][1]; } }); } return s; }
重大变化:
>正则表达式模式不区分大小写(请参阅i modifier)>如果匹配的字符为大写,则返回大写的字符变体(match.toUpperCase()=== match)