Jacob Pedersen
Jacob Pedersen

Reputation: 347

Javascript variable/string functions?

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

Answers (2)

Josh
Josh

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

Abraham Hamidi
Abraham Hamidi

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.

Demo


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.

Demo

Upvotes: 3

Related Questions