- In Javascript Write a function named givenName with one parameter named fullNa
ID: 3914396 • Letter: #
Question
- In Javascript Write a function named givenName with one parameter named fullName. The parameter fullName will always contain a person’s family and given names in that order separated by a comma and a single space, for example "Reagan, Ronald" (without the quotation marks). The function should extract and return the person’s given name, for example "Ronald" (without the quotation marks).
- In Javascript Write a function named prefix that returns the common prefix of two strings. For example, the common prefix of "disable" and "distasteful" is "dis". This function takes two parameters and returns the common prefix.
Explanation / Answer
Both functions:
function givenName(s)
{
return s.split(", ")[1];
}
function prefix(s1, s2)
{
var p = "";
var l1 = s1.length;
var l2 = s2.length;
var n;
if(l1<l2)
n = l1
else
n = l2
var i = 0;
for(i=0; i<n; i++)
{
if(s1[i] != s2[i])
return p;
p = p + s1[i];
}
return p;
}
HTML Code:
<html>
<head>
</head>
<body>
<script>
document.write(givenName("Reagan, Ronald<br>"));
document.write(prefix("disable", "distasteful"));
function givenName(s)
{
return s.split(", ")[1];
}
function prefix(s1, s2)
{
var p = "";
var l1 = s1.length;
var l2 = s2.length;
var n;
if(l1<l2)
n = l1
else
n = l2
var i = 0;
for(i=0; i<n; i++)
{
if(s1[i] != s2[i])
return p;
p = p + s1[i];
}
return p;
}
</script>
</body>
</html>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.