DEV Community

loading...

Discussion on: Daily Challenge #1 - String Peeler

Collapse
aaron_stroud profile image
Aaron Stroud

I see a lot of solutions removing characters without checking to see if they're "letters." Here's my JavaScript solution.

// Remove the first and last _letters_ in a string
function removeFirstLastLetters(str) {
  if (str.length < 3) {
    return null;
  }
  else {
    const regex = /[a-zA-Z]/;

    let firstCharIndex = str.search(regex);

    if (firstCharIndex === -1 ) {
      return null;
    }

    else {
      let lastCharIndex = str.length - str.split("").reverse().join("").search(regex);

      return str.slice(0, firstCharIndex) + str.slice(firstCharIndex + 1, lastCharIndex - 1) + str.slice(lastCharIndex, str.length);
    }
  }
}