Mino
Mino

Reputation: 3

function within function js

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);

Upvotes: 0

Views: 59

Answers (1)

Joe Warner
Joe Warner

Reputation: 3452

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

Upvotes: 1

Related Questions