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
str
, as that hides the name of the type/function of the same name - abarnert 2014-01-02 20:04
$
, *
, #
, or &
, instead of just any instance of &
, is to use the character class [$*#&]
- abarnert 2014-01-02 20:06
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.
There's lodash's trim()
Removes leading and trailing whitespace or specified characters from string.
_.trim(' abc '); // → 'abc'
_.trim('-_-abc-_-', '_-'); // → 'abc'
Modifying a code snippet from Mozilla Developer Network String.prototype.trim(), you could define such a function as follows.
if (!String.prototype.strip) {
String.prototype.strip = function (string) {
var escaped = string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return this.replace(RegExp("^[" + escaped + "]+|[" + escaped + "]+$", "gm"), '');
};
}
It's not necessary and probably not advisable to put this function in the object String.prototype
, but it does give you a clear indication of how such a function compares with the existing String.prototype.trim()
.
The value of escaped
is as in the function escapeRegExp
in the guide to Regular Expressions. The Java programming language has a standard library function for that purpose, but JavaScript does not.
&
at the start and end, he just apparently didn't know how to use a character class to strip any of [*#&]
. Your answer fixes that, but doesn't explain what it's doing differently from his attempt - abarnert 2014-01-02 20:07
Not exactly... I would use regex for complicated string manipulation or the Slice() method to remove characters at certain points Slice() explained
str.replace(/(^\s*&)|(&\s*$)/g, '')
to remove preceding and trailing instance of&
. But what will be the regex in case of several characters - jerrymouse 2014-01-02 19:56