Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 313
jerrymouse Avatar asked Jan 02 '14 19:01

jerrymouse


2 Answers

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.

like image 194
Guffa Avatar answered Oct 21 '22 03:10

Guffa


There's lodash's trim()

Removes leading and trailing whitespace or specified characters from string.

_.trim('  abc  ');             // → 'abc'

_.trim('-_-abc-_-', '_-');     // → 'abc'
like image 40
jfunk Avatar answered Oct 21 '22 02:10

jfunk