w3resource

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

JavaScript Basic: Exercise-59 with Solution

Extract First Half of Even-Length String

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

This JavaScript program takes an input string with an even number of characters and returns a new string containing only the first half of the original string.

Visual 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" 

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"));

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that checks if a string has an even number of characters and returns its first half, otherwise returns an error message.
  • Write a JavaScript function that trims whitespace from an even-length string and then extracts its first half.
  • Write a JavaScript program that verifies if a string is even in length and extracts the first half using substring methods.

Go to:


PREV : Four Copies of Last 3 Characters.
NEXT : Remove First and Last Characters in String.

Improve this sample solution and post your code through Disqus.

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.