2
0

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で全角文字を半角文字に変換

Posted at

#全角文字を半角文字に変換

全角文字の文字コードから65248個前の文字コードが半角文字になるようです。
 (全角スペース)の65248個前に変換すると違う文字になってしまうのでifで判断し返しています。

.js
const FULL_STR = 'ABCabc123()、 '
                                     // ↑ 全角スペース
  const conversion = (str) => {
                                    // ↓ 全角スペース
    str.replace(/[A-Za-z0-9 () 、 ]/g, (c) => {
      if (c === '') { return ',' }
      if (c === ' ') { return ' ' }
      return String.fromCharCode(c.charCodeAt(0) - 65248)
    })
    return str
  }
  
  const HALF_STR = conversion(FULL_STR)
  console.log(HALF_STR)

+ 65248にすれば半角文字を全角文字に変換することもできます。

感想

文字コード難しい。
JavaScriptの綺麗な書き方がわからない。もっと書くぞ!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?