Converting japanese fullwidth characters typed by user to halfwidth character in the same input field

  Kiến thức lập trình

There’s an input field, when the user will type any Fulwidth japanese character (numbers only) it won’t be displayed on that input field. It’ll be converted to it’s respective halfwidth character and, then that halfwidth character will be visible inside that same input field. I user type 0, this 0ill not be shown in the input field, it’ll show the converted halfwidth 0. In my case the problem is if the user type 0, the function is running twice and showing 00, but it should be only 0. Can anybody please help me to sort it out? i’m stucked here.

 <input type="text" id="inputField" oninput="convertToHalfWidth(this.value)">
<script>
        function convertToHalfWidth(input) {
            console.log(input);
            // Map of full-width to half-width numbers
            const fullToHalfMap = {
                '0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9'
            };

            // Replacing full-width numbers with their half-width counterparts
            const convertedInput = input.replace(/[0-9]/g, match => fullToHalfMap[match]);

            // Updating the input field with the converted value
            document.getElementById('inputField').value = convertedInput;
        }
    </script> here

New contributor

anik ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT