In: Computer Science
Hey, how do I create a function which receives one argument (string). The function would count and return the number of alphanumeric characters found in that string. function('abc 5} =+;d 9') // returns 6 in JavaScript?
CODE:
<!DOCTYPE html>
<html>
<head>
<title>Alnum Count</title>
</head>
<body>
<p id="input"></p> <! -- to print input-->
<p id="count"></p> <! -- to print count -->
<script>//script tag to write the function.
var string=prompt("Enter string : ");//taking input from the
user
document.getElementById("input").innerHTML="The user input is :
"+string;//printing the input.
var count=alnum(string);//function returnds the count of alpha
numeric characters.
//Printing the count returned from the function.
document.getElementById("count").innerHTML = "The count of alpha
numberic characters is : "+count;
//function that returns the count of alpha numeric.
function alnum(str) {
var i;//loop variable.
var count=0;//count variable.
for(i=0;i<str.length;i++)//loop iterates through
the string.
{
//condition to check number or
lowercase alphabet or uppercase alphabet.
if((str[i]>='0' &&
str[i]<='9') ||(str[i]>='a' && str[i]<='z')
||(str[i]>='A' && str[i]<='Z'))
{
++count;//increment count if condition satisfied
}
}
return count;//returning the count.
}
</script>
</body>
</html>
CODE ATTACHMENTS:
prompt:

OUTPUT:

Please do comment for any queries.
PLease like it.
Thank You.