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
You have to specify
return, so that the result of the operation is returned: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:
.splitsplits 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)