Remove First & Last Problem: JavaScript

·

2 min read

Remove first and last letter of a given string

The Problem

Create a JavaScript function that takes in a string & outputs a string without the first and last letter of the string removed.

If the given string was "reduce" the output would be "educ". If the string was "Fame" the output would be "am"

Things to note

In JavaScript, strings & numbers are both immutable. What's immutable mean? Once a variable has been declared as a string or number, it cannot be changed.

//we assign variable str to be equal to a string, "hello"
let str = "hello";
//we use the .toUpperCase() method to convert str to uppercase letters
str.toUpperCase();
//we log str to the terminal, then realize that str has NOT been changed
console.log(str);
//outputs "hello" which is the original value of str

So, how do we get around this? We need to either declare a new variable or reassign the original variable.

let str = "hello";

//Declare new variable
let newStr = str.toUpperCase();
console.log(newStr);
//outputs "HELLO"

//Reassign original variable
str = str.toUpperCase();
console.log(str);
//outputs "HELLO"

Back to the problem

There are several solutions to this problem, but I will walk through my original solution. First we want to create our function, this function will take in a string.

function removeFirstAndLast(str){
}

Then we want to remove the first letter and the last letter of a given string, I did this by creating a new variable and using the replace method, then I slice the last letter. We could use slice two times in a row, but we can use both to show off more methods.

function removeFirstLast(str) {
    let newString = str.replace(str[0], "").slice(0, -1)
    return newString
}

And there's my solution.