Monday, 6 February 2017

JavaScript function to find a character and print the position of it

Here is a script which prints the position of the character in a given string. Here using charAt() built in function to traverse the characters.

<!DOCTYPE html>
<html>
<body>
<lable>Enter the string here : </lable>
 <input type="text" name="enter" id="text" value=""/>
<br/>
<lable>Enter the character to find : </lable>
 <input type="text" name="enter" id="char1" value=""/>
<br/>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() 
{
var str =  document.getElementById('text').value;
var len = str.length;
var mychar = document.getElementById('char1').value;
var k=0;
for(var i=0; i<len;i++)
 {
 search = str.charAt(i);
    if (search == mychar)
    {
     alert("Found at position = " + i);
    }
 }
}
</script>
</body>
</html>

Try Output Here :
Enter the string here :


Enter the character to find :



No comments:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2016