JavaScript: Middle character(s) of a string
JavaScript Math: Exercise-86 with Solution
Write a JavaScript program to get the middle character(s) from a given string.
Test Data:
("abcd") -> "bc"
("abc") -> "b"
("JavaScript") -> "Sc"
Sample Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript program to Middle character(s) of a string</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function test(text) {
var text_len = text.length;
if (text_len % 2 != 0)
{
let start = (text_len - 1) / 2;
return text.slice(start, start + 1)
}
else
{
let start = text_len / 2 - 1;
return text.slice(start, start + 2);
}
}
text = "abcd"
console.log("Original string: "+text);
console.log("Middle character(s) of the said string: "+test(text))
text = "abc"
console.log("Original string: "+text);
console.log("Middle character(s) of the said string: "+test(text))
text = "JavaScript"
console.log("Original string: "+text);
console.log("Middle character(s) of the said string: "+test(text))
Sample Output:
Original string: abcd Middle character(s) of the said string: bc Original string: abc Middle character(s) of the said string: b Original string: JavaScript Middle character(s) of the said string: Sc
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-86 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Sum of the main diagonal elements of a square matrix.
Next: Check a number is Sastry number or not
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join