2
1

More than 1 year has passed since last update.

javascript で全角英数記号を半角にする

Last updated at Posted at 2022-06-21

123456 -> 123456 みたいな変換をしたい場合のコード。
style="ime-mode: off" を書いてもchromeだとシカとされる。
そんな場合に input type="tel" を使おう、なんて言う記事も多いけど tel でもないのに tel を使うの気持ち悪いので focus out時とかにフィルター通して正規化しよう、って魂胆。

var filters = filters || (function () {
    const FullWidthStart = 0xff00
    const FullWidthEnd  = 0xff7e;
    const HalfWidthStart = 0x20;
    // ascii 文字はそのまま通す
    const AsciiEnd = 0x7f;
 
    return {
        toNarrow: function(s){
            let  result = '';
            for(let i = 0; i < s.length; i++){
                let c = s.charCodeAt(i);
                // ascii 文字はそのまま通す
                if(c < AsciiEnd){
                  result += String.fromCharCode(c);
                  // ここで戻らないと!
                  continue;  
                }
                if(c < FullWidthStart || FullWidthEnd < c){
                    continue;
                }
                let code = c - FullWidthStart + HalfWidthStart;
                result += String.fromCharCode(code);
            }   
            return result;
        }
    }
})();

let halfStrings = filters.toNarrow('1234567890abcdefghijzABCDEZあいうえお憂鬱な空!”#$%&’()=~');
console.log(halfStrings);
2
1
5

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
2
1