jerrymouse jerrymouse - 4 months ago 10
Python Question

Is there a python strip function equivalent in javascript?

Python's strip function is used to remove given characters from the beginning and end of the string. How to create a similar function in javascript?

Example:

str = "'^$ *# smart kitty & ''^$* '^";
newStr = str.strip(" '^$*#&");
console.log(newStr);


Output:

smart kitty

Answer

A simple but not very effective way would be to look for the characters and remove them:

function strip(str, remove) {
  while (str.length > 0 && remove.indexOf(str.charAt(0)) != -1) {
    str = str.substr(1);
  }
  while (str.length > 0 && remove.indexOf(str.charAt(str.length - 1)) != -1) {
    str = str.substr(0, str.length - 1);
  }
  return str;
}

A more effective, but not as easy to use, would be a regular expression:

str = str.replace(/(^[ '\^\$\*#&]+)|([ '\^\$\*#&]+$)/g, '')

Note: I escaped all characters that have any special meaning in a regular expression. You need to do that for some characters, but perhaps not all the ones that I escaped here as they are used inside a set. That's mostly to point out that some characters do need escaping.