ROHIT MANDALAPU ROHIT MANDALAPU - 4 years ago 73
Javascript Question

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

Answer Source

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download