69
53

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptの文字列を全部小文字/大文字化する

Last updated at Posted at 2014-10-17
var lower = 'ABCabc'.toLowerCase();
var upper = 'ABCabc'.toUpperCase();

ただし、String#toLowerCase と String#toUpperCase はブラウザーのロケーション設定がトルコだと正しい結果を返さないので、代替処理を行う必要がある。

function manualLowercase(s) {
  return s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);});
};
function manualUppercase(s) {
  return s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);});
};

var lower = manualLowercase('ABCabc');
var upper = manualUppercase('ABCabc');

代替処理を行うかどうかの判定は下記のコードで行う。

if ('i' !== 'I'.toLowerCase()) {
  // 代替処理を行う
} else {
  // toLowerCase(), toUpperCase()を使う
}

じゃあ面倒くさいから全部代替処理をすればいいのか?というとそうでもなくて、
代替処理の方が動作が遅いので可能な限りは通常のtoLowerCase(), toUpperCase()を使うべきなのです。

…というのをAngularJSのコードを読んでて見つけました。こんなの日本に住んでたら絶対わかんないよなー。

69
53
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
69
53

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?