Write a program to print a letter in the middle when given a string. If the length of a string is even number, print two middle letters.
Result Example
Solution
- To get the index of middle letter, get the quotient of the length of string divided by 2 and store it in the variable 'mid'.
- If the length of the string is an odd number, the index of the middle letter will be the value of 'mid'. Get the middle letter using substring() method and store it in the answer variable.
String.prototype.substring() The substring() method returns the part of the string between the start and end indexes, or to the end of the string.
- If the length of the string is an even number, the index of the middle letters will have the index of mid-1 and mid. Get the two middle letters using same method and store it in the answer variable.
- Return 'answer'.
function solution(str){
let answer;
let mid = Math.floor(str.length / 2)
if (str.length % 2 === 1){
answer = str.substring(mid, mid+1);
} else {
answer = str.substring(mid-1, mid+1);
}
return answer;
}