w3resource

JavaScript: Create a new string without the first and last character of a given string

JavaScript Basic: Exercise-60 with Solution

Write a JavaScript program to create a new string without the first and last characters of a given string.

This JavaScript program takes an input string and returns a new string with the first and last characters removed. The length of the input string should be at least 2.

Visual Presentation:

JavaScript:  Create a new string without the first and last character of a given string

Sample Solution:

JavaScript Code:

// Define a function named without_first_end with parameter str
function without_first_end(str) {
  // Use substring to get a portion of the string excluding the first and last characters
  return str.substring(1, str.length - 1);
}

// Call the function with sample arguments and log the results to the console
console.log(without_first_end('JavaScript'));
console.log(without_first_end('JS'));
console.log(without_first_end('PHP')); 

Output:

avaScrip

H

Live Demo:

See the Pen JavaScript - Create a new string without the first and last character of a given string - basic-ex-60 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Create a new string without the first and last character of a given string

ES6 Version:

// Define a function named without_first_end with parameter str
const without_first_end = (str) => {
    // Use substring to get a substring excluding the first and last characters
    return str.substring(1, str.length - 1);
};

// Call the function with sample arguments and log the results to the console
console.log(without_first_end('JavaScript'));
console.log(without_first_end('JS'));
console.log(without_first_end('PHP'));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to extract the first half of a string of even length.
Next: JavaScript program to concatenate two strings except their first character.

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-basic-exercise-60.php