JavaScript 中的土耳其语大小写转换

我想在我想要的语言环境中将字符串转换为 JavaScript 中的小写或大写.我认为像 toUpperCase()toLocaleUpperCase() 这样的标准函数不能满足这个需求.toLocale 函数的行为不正常.

I want to convert strings to lower or upper case in JavaScript in the locale I wanted. I think standard functions like toUpperCase() and toLocaleUpperCase() do not satisfy this need. toLocale functions do not behave as they should.

例如,在我的系统上的 Safari 4、Chrome 4 Beta、Firefox 3.5.x 中,它会错误地转换带有土耳其字符的字符串.浏览器对 navigator.language 的响应分别为 "en-US""tr""en-US".但据我所知,无法在浏览器中获取用户的 Accept-Lang 设置.只有 Chrome 给了我 "tr" 虽然我已经配置了每个浏览器的首选土耳其语言环境.我认为这些设置只会影响 HTTP 标头,但我们无法通过 JavaScript 访问这些设置.

For example, in Safari 4, Chrome 4 Beta, Firefox 3.5.x on my system it converts strings with Turkish characters incorrectly. The browsers respond to navigator.language as "en-US", "tr", "en-US" respectively. But there is no way to get user's Accept-Lang setting in the browser as far as I could found. Only Chrome gives me "tr" although I have configured every browser Turkish locale preferred. I think these settings only affect HTTP header, but we can't access to these settings via JavaScript.

在 Mozilla 文档中它说

字符串中的字符在遵守当前语言环境的情况下转换为 ....对于大多数语言,这将返回与 ...

The characters within a string are converted to ... while respecting the current locale. For most languages, this will return the same as ...

我认为它对土耳其语有效,它配置为 en 或 tr 并没有什么不同.在土耳其语中,它应该将 "DİNÇ" 转换为 "dinç""DINÇ" 转换为 "dınç" 或反之- 反之亦然.

I think it's valid for Turkish, it doesn't differ it's configured as en or tr. In Turkish it should convert "DİNÇ" to "dinç" and "DINÇ" to "dınç" or vice-versa.

是否有任何 JavaScript 库可以满足这种需求?我认为它不仅应该在用户的语言环境中正确转换,还应该支持通过语言环境参数进行转换.因为开发人员无法访问用户配置的首选语言.

Is there any JavaScript library that satisfies this need? I think it should not only converting correctly in user's locale, but also it should support conversion via a locale parameter. Because developers cannot access to user's configured preferred language.

推荐答案

多年后再回来提供更多最新的解决方案.

Coming back to this years later to provide more up to date solution.

下面不需要破解,

只需使用String.toLocaleUpperCase() 和 String.toLocaleLowerCase()

"dinç".toLocaleUpperCase('tr-TR') // "DİNÇ"

所有现代浏览器现在都支持这个.

All modern browsers support this now.

[旧的,不要使用这个]

[ OLD, DO NOT USE THIS ]

试试这些功能

String.prototype.turkishToUpper = function(){
    var string = this;
    var letters = { "i": "İ", "ş": "Ş", "ğ": "Ğ", "ü": "Ü", "ö": "Ö", "ç": "Ç", "ı": "I" };
    string = string.replace(/(([iışğüçö]))+/g, function(letter){ return letters[letter]; })
    return string.toUpperCase();
}

String.prototype.turkishToLower = function(){
    var string = this;
    var letters = { "İ": "i", "I": "ı", "Ş": "ş", "Ğ": "ğ", "Ü": "ü", "Ö": "ö", "Ç": "ç" };
    string = string.replace(/(([İIŞĞÜÇÖ]))+/g, function(letter){ return letters[letter]; })
    return string.toLowerCase();
}

// Example
"DİNÇ".turkishToLower(); // => dinç
"DINÇ".turkishToLower(); // => dınç

我希望它们对你有用.

相关文章