Write a JavaScript program to read a character string from user and perform the following functions: a. Accept a character from user and count the number of occurrences of that character in the string. b. Accept a Position from user and print the character at specified position. (Use promt() function for accepting a character)

 Preview- Click on image


Code-

Note - Save This File as index.html

<!DOCTYPE html>

<html>

<head>

<title>Slip6</title>

</head>

<body>

<script>

function cal() {

var r1=document.forms[0];

var a=document.frm.txt.value;

var repeat=0;

var c;

if(r1[1].checked)

{

c=prompt("Enter character: ");

for(i=0;i<a.length;i++)

{

if(a[i]==c)

{

repeat=repeat+1;

}

}

alert("Total number of occurences: "+repeat);

}

if(r1[2].checked)

{

var pos=prompt("Enter Position: ");

var ch=a.charAt(parseInt(pos)-1);

if(ch!="")

alert("character at specified position is: "+ch);

else

alert("Please Enter value between "+ a.length);

}

}

</script>

<form name="frm">

Enter the string: <input type="text" name="txt" ><br/>

<input type="radio" name="r1" id="t1">Accept a character from user and count the number of occurrences of that

character in the string.<br/>

<input type="radio" name="r1" id="t2">Accept a Position from user and print the character at specified position.<br/>

<input type="button" onclick ="cal()" name="b1" value="Submit">

</form>

</body>

</html>

0 Comments