w3resource

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:

JavaScript Code:

/**
 * Function to find the middle character(s) of a given string.
 * @param {string} text - The input string.
 * @returns {string} - The middle character(s) of the string.
 */
function test(text) {
    // Get the length of the input string
    var text_len = text.length;
    // Check if the length of the string is odd or even
    if (text_len % 2 != 0) {
        // Calculate the start index for odd-length strings
        let start = (text_len - 1) / 2;
        // Return the middle character
        return text.slice(start, start + 1);
    } else {
        // Calculate the start index for even-length strings
        let start = text_len / 2 - 1;
        // Return the middle two characters for even-length strings
        return text.slice(start, start + 2);
    }
}
// Test cases
// Assign value to text
text = "abcd";
// Print the original string
console.log("Original string: " + text);
// Print the middle character(s) of the said string
console.log("Middle character(s) of the said string: " + test(text));
// Repeat the above steps for different values of 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));

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:

JavaScript: Middle character(s) of a string.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-math-exercise-86.php