JavaScript that Uses Functions String and Number

Aim:

Develop and demonstrate a HTML5 file that includes JavaScript script that uses functions for the following problems:

  1. Parameter: A string
    • Output: The position in the string of the left-most vowel
  2. Parameter: A number
    • Output: The number with its digits in the reverse order

Explanation:

This program demonstrates the structure of HTML5 files and the semantic structure followed. The writing of functions in Javascript and form-based event handling in Java script is also illustrated. The dynamic processing of Javascript without reloading HTML5 pages is also shown.

Code:

Html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demonstrating Java script functions</title> </head>
<script type=text/javascript src=4.js>
</script>
<body>
<section>
<h1>Finding left most vowel</h1>
<p>Enter a string: <input type=text id=t1></p>
<input type=button value=Find onclick = alert( findLMV(
document.getElementById('t1').value ))>
</section>
<hr>
<section>
<h1>Reverse of a number</h1>
<p>Enter a number: <input type=text id=t2></p>
<input type=button value=Reverse
onclick=alert(reverse(document.getElementById('t2').value))>
</section>
</body>
</html>

JavaScript

function findLMV(str)
{
for(i=0;i<str.length;i++)
{
if(str.charAt(i)=='a' || str.charAt(i)=='e' || str.charAt(i)=='i' ||str.charAt(i)=='o' || str.charAt(i)=='u' )
return ("Left most vowel of " + str + " is at location " + (i+1) );
}
return ("No vowels found for string "+ str);

}

function reverse(num)
{
rnum=0; temp=num; if(isNaN(num))
{
return "invalid number";
}
while(num!=0)
{
rnum *= 10; rnum+= num % 10; num -= num % 10;
num = Math.floor(num/10);
}
return "Reverse of num "+ temp + " is " + rnum;
}

Javascript functions used:

charAt() – The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

Math.floor() – The floor() method rounds a number DOWNWARDS to the nearest integer and returns the result. If the passed argument is an integer, the value will not be rounded.

Leave a Comment