Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set locale in JavaScript, for example for toLocaleUpperCase()?

I'd like to use the JavaScript toLocaleUpperCase() method to make sure that the capitalization works correctly for the Turkish language. I cannot be sure, however, that Turkish will be set as the user's locale.

Is there a way in modern browsers to set the locale in run time, if I know for sure that the string is in Turkish?

(I ran into this problem while thinking about Turkish, but actually it can be any other language.)

like image 675
Amir E. Aharoni Avatar asked Jan 27 '13 14:01

Amir E. Aharoni


3 Answers

There isn't really anything much out there but I came across this JavaScript setlocale function script that you might find useful.

like image 83
SimonDever Avatar answered Oct 18 '22 17:10

SimonDever


You unfortunately cannot set locale during runtime. All hope is not lost though, there are many good libraries on npm for you to use. Check out https://www.npmjs.com/package/upper-case and https://www.npmjs.com/package/lower-case for example, it will work for many other languages too.

If that's too much, you can roll your own simple library:

var ALL_LETTERS_LOWERCASE = 'abcçdefgğhıijklmnoöprsştuüvyz';
var ALL_LETTERS_UPPERCASE = 'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ';

function toLowerCaseLetter(letter) {
  letter_index = ALL_LETTERS_UPPERCASE.indexOf(letter);
  return ALL_LETTERS_LOWERCASE[letter_index];
}
    
function toLowerCase(my_str) {
  var lower_cased = ''
  for (letter of my_str) {
      lower_cased += toLowerCaseLetter(letter);
  }
  return lower_cased;
}

console.log(toLowerCase('ÇDEFGĞHIİJKLMNOÖPRSŞTUÜ'))

Very similar for upper case version.

like image 22
tayfun Avatar answered Oct 18 '22 15:10

tayfun


This option may not have existed back in 2013 but may help new visitors on this topic:

According to MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase) the function toLocaleUpperCase takes an optional parameter 'locale'.

Setting the right language tag is a topic on its own (https://www.w3.org/International/articles/language-tags/). Simplest example looks like this

'selam dünya'.toLocaleUpperCase('tr'); // SELAM DÜNYA
like image 22
Bernard Perrin Avatar answered Oct 18 '22 16:10

Bernard Perrin