I'm trying to create a simple prototype in JavaScript that removes a character from a string (like Python's strip). This may well exist already in JavaScript, but I can't find it and this is more of an exercise for me than a replacement for something that already exists.
function strip(chars) {
this.replace(chars,"");
}
String.prototype.strip=strip;
var wrong = "Hellow";
alert(wrong.strip("w"));
When I run this code, the alert says "Undefined". My suspicion is the this. in the function but not sure. I've also made a fiddle here: http://jsfiddle.net/jdb1991/rapxM/
Thanks
2 Answers 2
You have to specify return, so that the result of the operation is returned:
function strip(chars) {
return this.replace(chars,"");
}
Working demo: http://jsfiddle.net/rapxM/1/
Notice that your code does not remove all characters, it does only remove the first occurrence. If you want to remove all characters, use:
function strip(chars) {
return this.split(chars).join('');
}
3 Comments
strip doesn't remove occurrences from the middle of the string (docs.python.org/library/stdtypes.html#str.strip). Don't know what @jdborg actually wants.strip method, he can either switch to a Regular Expression, or trim the characters in two loops.If you want to have the same behavior as Python's strip, you should only remove characters from the start and end of the string. Here is a solution with regular expressions that accomplishes this:
function strip(chars, wholeString) {
if (wholeString)
chars = "(" + chars + ")*";
else
chars = "[" + chars + "]*";
var pattern = "^" + chars + "|" + chars + "$";
return this.replace(new RegExp(pattern, "g"),"");
}
If wholeString is set to true, it will treat chars as a block of characters that have to occur together (your question seemed to ask for that), while if not set (the default), each character in chars will be removed on its own (like in Python). Use it like this:
String.prototype.strip=strip;
var str = "ababccabcccbbab";
document.write(str.strip("ab")); // -> "ccabccc"
document.write(str.strip("ab", true)); // -> "ccabcccbb"
Note that ab is not removed from the middle of str. In the first call, a and b are treated separately, so bb is also stripped.