w3resource

JavaScript: Extract the first half of a string of even length

JavaScript Basic: Exercise-59 with Solution

Write a JavaScript program to extract the first half of a even string.

Pictorial Presentation:

JavaScript:  Extract the first half of a string of even length

Sample Solution:

JavaScript Code:

// Define a function named first_half with parameter str
function first_half(str) {
    // Check if the length of the string is even
    if (str.length % 2 == 0) {
        // Use the slice method to get the first half of the string
        return str.slice(0, str.length / 2);
    }
    // If the length is odd, return the original string
    return str;
}

// Call the function with sample arguments and log the results to the console
console.log(first_half("Python"));       // Outputs "Py"
console.log(first_half("JavaScript"));   // Outputs "Java"
console.log(first_half("PHP"));           // Outputs "PHP" 

Sample Output:

Pyt
JavaS
PHP

Live Demo:

See the Pen JavaScript - Extract the first half of a string of even length - basic-ex-59 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Extract the first half of a string of even length

ES6 Version:

// Define a function named first_half with parameter str
const first_half = (str) => {
    // Check if the length of the string is even
    if (str.length % 2 === 0) {
        // Use slice to get the first half of the string
        return str.slice(0, str.length / 2);
    }
    // Return the original string if the length is odd
    return str;
};

// Call the function with sample arguments and log the results to the console
console.log(first_half("Python"));
console.log(first_half("JavaScript"));
console.log(first_half("PHP"));

Previous: JavaScript program to create a new string of 4 copies of the last 3 characters of a given original string.
Next: JavaScript program to create a new string without the first and last character of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.