Turkish case conversion in JavaScript

对着背影说爱祢 提交于 2019-11-28 05:49:31

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

There is no need for the hack below,

just use String.toLocaleUpperCase() and String.toLocaleLowerCase()

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

All browsers support this now.


[ OLD, DO NOT USE THIS ]

Try these functions

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ç

I hope they will work for you.

Thanks for the function. I really liked it. Consecutive Turkish char input results 'undefined' as 'ÇÇ'. Try replacing '/+g' with '/g'. The functions would be:

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();
}
cihan
String.prototype.tUpper = function(){
   return this.replace(/i/g,"İ").toLocaleUpperCase();
}

String.prototype.tLower = function(){
    return this.replace(/I/g,"ı").toLocaleLowerCase();
}

Please look into this small piece of code that can convert to upppercase and lowercase

var manualLowercase = function(s) {
  return isString(s)
      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
      : s;
};

var manualUppercase = function(s) {
  return isString(s)
      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
      : s;
};
    var  a="lişliş lğüğpğp İŞİŞİŞ lşi ĞĞHFGH ÜGFHFHG ühüüüğ üğüğş ş ş Ş  İ i  ılk Ilk";

var s=a.split(' ');

var netice="";

s.forEach(function(g) {
  if (g.length>1)
    netice+=g[0].toLocaleUpperCase('tr')+
      g.slice(1).toLocaleLowerCase('tr')+" "; 
  else
    netice+=g.toLocaleUpperCase('tr')+" ";
});

alert(netice); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!