如何从字符串中删除重音字符?
特别是在IE6中,我有这样的东西:
accentsTidy = function(s){
var r=s.toLowerCase();
r = r.replace(new RegExp(/\s/g),"");
r = r.replace(new RegExp(/[àáâãäå]/g),"a");
r = r.replace(new RegExp(/æ/g),"ae");
r = r.replace(new RegExp(/ç/g),"c");
r = r.replace(new RegExp(/[èéêë]/g),"e");
r = r.replace(new RegExp(/[ìíîï]/g),"i");
r = r.replace(new RegExp(/ñ/g),"n");
r = r.replace(new RegExp(/[òóôõö]/g),"o");
r = r.replace(new RegExp(/œ/g),"oe");
r = r.replace(new RegExp(/[ùúûü]/g),"u");
r = r.replace(new RegExp(/[ýÿ]/g),"y");
r = r.replace(new RegExp(/\W/g),"");
return r;
};
但是IE6让我很烦,它好像不喜欢我的正则表达式。
将一个用户定义的函数传递给Array.sort()方法,并在这个用户定义的函数中使用String.localeCompare()
function myCompareFunction(a, b) {
return a.localeCompare(b);
}
var values = ["pêches", "épinards", "tomates", "fraises"];
// WRONG: ["fraises", "pêches", "tomates", "épinards"]
values.sort();
// **GOOD**: ["épinards", "fraises", "pêches", "tomates"]
values.sort(myCompareFunction);
新RegExp的格式为
RegExp(something, 'modifiers');
所以你会想
accentsTidy = function(s){
var r=s.toLowerCase();
r = r.replace(new RegExp("\\s", 'g'),"");
r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
r = r.replace(new RegExp("æ", 'g'),"ae");
r = r.replace(new RegExp("ç", 'g'),"c");
r = r.replace(new RegExp("[èéêë]", 'g'),"e");
r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
r = r.replace(new RegExp("ñ", 'g'),"n");
r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
r = r.replace(new RegExp("œ", 'g'),"oe");
r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
r = r.replace(new RegExp("\\W", 'g'),"");
return r;
};
替换变音符的一种更简单的方法。
function replaceDiacritics(str){
var diacritics = [
{char: 'A', base: /[\300-\306]/g},
{char: 'a', base: /[\340-\346]/g},
{char: 'E', base: /[\310-\313]/g},
{char: 'e', base: /[\350-\353]/g},
{char: 'I', base: /[\314-\317]/g},
{char: 'i', base: /[\354-\357]/g},
{char: 'O', base: /[\322-\330]/g},
{char: 'o', base: /[\362-\370]/g},
{char: 'U', base: /[\331-\334]/g},
{char: 'u', base: /[\371-\374]/g},
{char: 'N', base: /[\321]/g},
{char: 'n', base: /[\361]/g},
{char: 'C', base: /[\307]/g},
{char: 'c', base: /[\347]/g}
]
diacritics.forEach(function(letter){
str = str.replace(letter.base, letter.char);
});
return str;
};