Search code examples
javascriptstringsubstringcomparisonindexof

How to create a new string from a given string, removing the first and last characters of the string if the first or last character are 'P'?


I have to create a program creates a new string from a given string, removing the first and last characters of the string if the first or last character are 'P'. Then return the original string if the condition is not satisfied. The code I wrote does not throw an error, but clearly the if condition is wrong since the code is always returning only the str. Could someone clarify what's the issue?

function remove(str) {
if (str.indexOf(0) === "p" && str.indexOf(-1) === "p") {
return str.substring(1, str.length - 1);
} else {
return str;
}
}

console.log(remove("pparallelepipedp"));

Solution

  • From my above comments ...

    "The OP seems to not have read the documentation of String.prototype.indexOf. Of cause neither of the conditions 'pparallelepipedp'.indexOf(0) === "p" and 'pparallelepipedp'.indexOf(-1) === "p" will ever fulfill."

    "... The OP might try charAt, maybe even at (where the latter supports the -1 parameter value) instead."

    function removeWithHelpOfCharAt(str) {
      // the OP's code with the help of `charAt`.
      if (str.charAt(0) === 'p' && str.charAt(str.length - 1) === 'p') {
    
        return str.substring(1, str.length - 1);
      } else {
        return str;
      }
    }
    console.log(
      "removeWithHelpOfCharAt('pparallelepipedp') ...",
      removeWithHelpOfCharAt('pparallelepipedp')
    );
    console.log(
      "removeWithHelpOfCharAt('Pparallelepipedp') ...",
      removeWithHelpOfCharAt('Pparallelepipedp')
    );
    
    function removeWithHelpOfAt(str) {
      // the OP's code with the help of `at` ...
      // ... and a slightly changed way of returning the result.
      if (str.at(0) === 'p' && str.at(-1) === 'p') {
    
        str = str.substring(1, str.length - 1);
      }
      return str;
    }
    console.log(
      "removeWithHelpOfAt('pparallelepipedp') ...",
      removeWithHelpOfAt('pparallelepipedp')
    );
    console.log(
      "removeWithHelpOfAt('Pparallelepipedp') ...",
      removeWithHelpOfAt('Pparallelepipedp')
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }