Home > Back-end >  How to create a new string from a given string, removing the first and last characters of the string
How to create a new string from a given string, removing the first and last characters of the string

Time:11-02

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

CodePudding user response:

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

CodePudding user response:

I would go with slice:

function remove(str) {
        if (str[0] === "p" && str.slice(-1) === "p") {
            return str.slice(1, -1);
        }
        
        return str
    }
    
console.log(remove("pparallelepipedp"));    // Returns: parallelepiped
console.log(remove("oparallelepipedp"))     // Returns: oparallelepipedp
console.log(remove("pparallelepipedo"));    // Returns: pparallelepipedo

You could also consider a regex validation. You can experiment with regex here: https://regex101.com/

In your case you could do:

var regExp = /^p(.*?)p$/;

function remove(str) {
    return regExp.test(str) ? str.slice(1, -1) : str
}

console.log(remove('pparallelepipedp')); // Returns: parallelepiped
console.log(remove('oparallelepipedp')); // Returns: oparallelepipedp
console.log(remove('pparallelepipedo')); // Returns: pparallelepipedo

CodePudding user response:

The function indexOf returns the index of the item you pass as the param.

So str.indexOf(0) will try to find 0 in the str and return its index, if not found it'll return -1.

You can get more understanding of indexOf by playing with examples here https://www.w3schools.com/jsref/jsref_indexof.asp

So instead of using indexOf you need to use any other method through which you can access values on those specific indexes.

The code I wrote is to make things easier so we can easily perform our required actions

const remove = (str) => {
   // This will convert the string into an array
   // https://www.w3schools.com/jsref/jsref_split.asp
    str = str.split('');

    // Checking if value on first index is P
    if (str[0] == 'P'){
        // This function will remove the value on first index
        // https://www.w3schools.com/jsref/jsref_shift.asp
        str.shift();
    }

    // Similarly check for if value on last index is P
    if (str[str.length - 1] == 'P') {
        // This will remove the value on last index
        // https://www.w3schools.com/jsref/jsref_pop.asp
        str.pop();
    }

    // Other wise join the array back and send it as is
    // https://www.w3schools.com/jsref/jsref_join.asp
    return str.join('');
};
  • Related