0

I'm trying to create a function that will remove first and last character from a string. Im converting the string into an array, and then I want to use shift() and pop() methods to remove the characters.

I seem to have a trouble with passing the splitStr variable that has array within to another function that will pop/shift the character.

What am I doing wrong?

let str = 'example';

let removeChar = function(str){
      let splitStr = str.split("");

      function popLast(splitStr){
        let popStr = splitStr.pop();
      }

      function shiftFirst(splitStr){
        let shiftStr = splitStr.shift();

      }

}

removeChar(str);
5
  • You're neither returning any value from your function nor use it at call. Commented Apr 4, 2018 at 16:05
  • what are you trying to do split then pop then shift it then return or are you wanting to return a function? Commented Apr 4, 2018 at 16:07
  • what is your expected outcome Commented Apr 4, 2018 at 16:07
  • Well, you're not invoking popLast() and siftFirsst() anywhere Commented Apr 4, 2018 at 16:10
  • @mino hope my answer helped Commented Apr 4, 2018 at 16:15

1 Answer 1

1

The problem is you're not exicuting your functions just creating a function called popLast and shiftFirst the calls are happening within the function but are never called.

create a function that will remove first and last character from a string

let str = 'example';

let removeChar = function(str){
      let splitStr = str.split("");
      splitStr.pop();
      splitStr.shift();
      return splitStr.join("")
}


console.log(removeChar(str));

but this isn't the best way to remove first and last letters from a string for that we can use splice()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

function removeChar(string) {
   return string.slice(1, -1);
}
console.log(removeChar("example"));

I'd suggest reading about the return keyword

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your time, this explains a lot!
any questions let me know feel like you know what you need to do but just fuzzy about details. break your problems down make it work then find better ways chances are the first way you do it is wrong but thats fine we're trying to understand first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.