1
0

リアルタイムでJavaScriptで平仮名を全角カタカナへ変換

Last updated at Posted at 2024-07-11

やり方①:ボタン押下で変換

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>フォーカスアウトとボタン押下時の全角カタカナ変換</title>
</head>
<body>
    <input type="text" id="inputField" placeholder="入力してください">
    <button onclick="convertToKatakana()">変換</button>

    <script>
        function toFullWidthKatakana(str) {
            return str.replace(/[\u3041-\u3096]/g, function(match) {
                // ひらがなを全角カタカナに変換
                return String.fromCharCode(match.charCodeAt(0) + 0x60);
            });
        }

        function convertToKatakana() {
            const inputField = document.getElementById('inputField');
            const inputValue = inputField.value;
            const convertedValue = toFullWidthKatakana(inputValue);
            inputField.value = convertedValue;
        }

    </script>
</body>
</html>

やり方②:フォーカスアウト時に変換

補足:実は「ボタン押下」という動作をするときに「フォーカスアウト」も発火するので、ここにもしonclick設定なしのボタンを配置したら、押下時にonBlur発火で変換できる

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>フォーカスアウト時の全角カタカナ変換</title>
</head>
<body>
    <input type="text" id="inputField" placeholder="入力してください">

    <script>
        function toFullWidthKatakana(str) {
            return str.replace(/[\u3041-\u3096]/g, function(match) {
                // ひらがなを全角カタカナに変換
                return String.fromCharCode(match.charCodeAt(0) + 0x60);
            });
        }

        function convertToKatakana() {
            const inputField = document.getElementById('inputField');
            const inputValue = inputField.value;
            const convertedValue = toFullWidthKatakana(inputValue);
            inputField.value = convertedValue;
        }

        document.getElementById('inputField').addEventListener('blur', convertToKatakana);

    </script>
</body>
</html>

やり方③:入力しながら変換

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>リアルタイム全角カタカナ変換</title>
</head>
<body>
    <input type="text" id="inputField" placeholder="入力してください">

    <script>
        function toFullWidthKatakana(str) {
            return str.replace(/[\u3041-\u3096]/g, function(match) {
                // ひらがなを全角カタカナに変換
                return String.fromCharCode(match.charCodeAt(0) + 0x60);
            });
        }

        function convertInputToKatakana() {
            const inputField = document.getElementById('inputField');
            const inputValue = inputField.value;
            const convertedValue = toFullWidthKatakana(inputValue);
            inputField.value = convertedValue;
        }

        document.getElementById('inputField').addEventListener('input', convertInputToKatakana);
    </script>
</body>
</html>

参考サイト

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