简体   繁体   中英

How to restrict counting "spaces, special characters and Enter" while counting charecters

I have written a code for counting number of characters in a given text box but unable to restrict the counter from counting the Spaces, Special Characters and Enter. My goal is to only count the alphabets and numbers eliminating other.

I had written a code for counting any type of character but not able to write code which can eliminate Spaces, Special Characters and Enter and count only alphabets and numbers. My code is as follows.

<script type="text/javascript">
    function countChars(countfrom, displayto) {
        var len = document.getElementById(countfrom).value.length;
        document.getElementById(displayto).innerHTML = len;
    }
</script>

<textarea id="data" cols="40" rows="5" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> Characters entered.

Please Help Me

This might help you.

<script type="text/javascript">
    function countChars(countfrom, displayto) {
        var val = document.getElementById(countfrom).value;

        val = val.replace(/[^a-zA-Z0-9]/igm, "");

        var len = val.length;

        document.getElementById(displayto).innerHTML = len;
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM