Reputation: 347
I am practicing code readability and "beautifying" my code, so I want to learn how to implement this.
I've seen other code do this, but I don't remember which or how they did it.
I want to create my own .string functions, like so:
var rmbrackets = new function() {
return String.replace(/\[.*?\]/g, "");
}
console.log("this is a [test]test!".rmbrackets);
I want the above to log "this is a test!". The above is just an example, I want to do this with many other functions.
How can i do this?
Upvotes: 2
Views: 59
Reputation: 44916
Well... you can modify the prototype property to add new functionality:
String.prototype.sayHello = function(){
return this + " Hello!";
}
"Blah".sayHello(); // "Blah Hello!"
Upvotes: 1
Reputation: 13809
Try
String.prototype.rmbrackets = function() {
return this.replace(/\[.*?\]/g, "");
};
This adds to the Object String's prototype.
Also, you'll need to add ()
to actually execute it, so the full code would be
String.prototype.rmbrackets = function() {
return this.replace(/\(.*?\)/g, "");
};
console.log("this is a (test)test!".rmbrackets());
In this example I edited your regex to match what you want to achieve.
If you agree with Matt Greer, then you could just create a function for this:
function rmbrackets(text)
{
return text.replace(/\(.*?\)/g, "");
};
console.log(rmbrackets("this is a (test)test!"));
Because if everyone did this, built in prototypes would get polluted pretty quickly. People would step over each other a lot. There is also the problem if browsers natively added a rmbrackets, you might shadow it. Other problems include unexpected properties showing up in for in loops and such. In general, the JS community has agreed to leave built in prototypes alone.
Upvotes: 3