Help us understand the problem. What is going on with this article?

JavaScriptで英数を全角/半角に変換する方法

More than 3 years have passed since last update.

概要

入力欄に入力された全角英数字をJavaScriptにて半角にする処理

英数字を半角にする場合

全角英数の文字コードから65248個前が半角英数の文字コードとなっている為、
文字コードから65248引いて変換します。

英数字を半角にする場合
//10進数の場合
str.replace(/[A-Za-z0-9]/g, function(s) {
    return String.fromCharCode(s.charCodeAt(0) - 65248);
});

//16進数の場合
str.replace(/[A-Za-z0-9]/g, function(s) {
    return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});

英数字を全角にする場合

全角にする場合は
文字コードから65248足して変換します。

英数字を全角にする場合
//10進数の場合
str.replace(/[A-Za-z0-9]/g, function(s) {
    return String.fromCharCode(s.charCodeAt(0) + 65248);
});

//16進数の場合
str.replace(/[A-Za-z0-9]/g, function(s) {
    return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);
});

備考
英字だけ、数字だけの場合は、replace内部[A-Za-z0-9]から必要のない部分を取り除く

yamikoo@github
・自分の投稿検索(タグ・ワード) http://qiita.com/search?q=yamikoo%40github+tag%3A http://qiita.com/search?q=yamikoo%40github+
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした