Home > katas > Remove First and Last Character (8kyu) [JavaScript]

Remove First and Last Character (8kyu) [JavaScript]


Chek kata on Codewars

Description:

It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.

Solution 1.1

Let's start with a naive solution. Solving with loop.

const removeChar = str => {
    let newStr = ''
    for(let i = 0; i < str.length; i++){
        if(i !== 0 && i !== str.length -1) {
            newStr += str[i]
        }
    }
    return newStr
}

Solution 1.2

We can make it a little bit cleaner. We can start our loop from the second character and end it earlier. In this case, we can omit if statement.

const removeChar = str => {
    let newStr = ''
    for(let i = 1; i < str.length - 1; i++) {
        newStr += str[i]
    }
    return newStr
}

Solution 2.1

A more efficient solution will be to use slice method.

const removeChar = str => {
    return str.slice(1, str.length - 1)
}

Solution 2.2

We can make it a little bit shorter.

const removeChar = str => str.slice(1, - 1)

Solution 3.1

Another solution will be to use substring.

const removeChar = str => str.substring(1, str.length -1)

Solution 4.1

Not the most efficient solution. But we can convert a string to an array and use array methods.

const removeChar = str => {
    const newStr = str.split('')
    newStr.shift()
    newStr.pop()
    return newStr.join('')
}

Solution 4.2

Same solution but with the spread operator.

const removeChar = str => {
    const newStr = [...str];
    newStr.shift()
    newStr.pop()
    return newStr.join('')
}

Solution 5.1

Also, we can use a regular expression here with the replace method.

const removeChar = (str) => str.replace(/^.|.$/g, '');
© 2021, Andrew Losseff