4
5

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 の正規表現の case insensitive は全角英数にも適用される

Last updated at Posted at 2016-02-24
全角で
"iPhone".match(/iphone/i);  // ["iPhone"]

べんり🎉

以下で動作確認

  • iOS 9.2.1 UIWebView
  • Google Chrome Version 48.0.2564.116 (64-bit)
  • node
    • v0.10.36 (AWS Lambda 上)
    • v5.5.0

補足

上のように case insensitive (iフラグ) を使うことで、半角全角各々で大文字 / 小文字に対応できますが、半角 ↔ 全角の両方にヒットさせたいときは、自分で両パターン用意してやる方法があります。

全角 ↔ 半角の相互変換

たとえば String に以下のように全角半角変換を生やす。

全角→半角にする
String.prototype.toHankaku = function () {
    return this.replace(/[A-Za-z0-9]/g, function (s) {
        return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
    });
};

"iPhone".toHankaku();  // "iPhone"
半角→全角にする
String.prototype.toZenkaku = function () {
    return this.replace(/[A-Za-z0-9]/g, function (s) {
        return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);
    });
};


"iPhone".toHankaku();  // "iPhone"
4
5
0

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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?