Reputation: 18343
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
Upvotes: 2
Views: 408
Reputation: 5560
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.
Upvotes: 0
Reputation: 348962
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('');
}
.split
splits the string in smaller pieces, based on the given argument (returned value: array)..join()
is an array method, which concatenates the array (returned value: string)Upvotes: 5