You can get the character (letter) at the nth index in a string by writing stringVar.charAt(n) or simply stringVar[n]. The returned value will be a string containing only one character (for example, "a"). The first character position is index 0, which causes the last one to be found at position stringVar.length - 1. In other words, an 8 character string has length 8, and its characters have positions 0 and 7. 1. Prompt the user for a string. 2. Write a function called three that will: take a string as a parameter return the 3rd character of the string 3. Display the original string and the result of the function, seperated by a colon (:), to the console. 4. Modify the function so that if the string is shorter than 3 characters it will return the string "too short". 5. Modify the function so that if the third character is a space it will return the word "space". Sample Output User enters "Canada", output: Canada: n; User enters "Of course
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Function</title>
</head>
<body>
<script type="text/javascript">
function show_char(str) {
if (str.length < 3) {
return "too short"
}
else {
let ch = str[2]
if (ch == " ") {
return "space"
}
else {
return ch
}
}
}
var str = prompt("input: ", "");
console.log(str + ": " + show_char(str))
</script>
</body>
</html>
Comments
Leave a comment