Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom replace method?

Tags:

javascript

Is it possible to create your own custom, I believe the term is 'method'? For example, something like this:

var str = "test"
str.replaceSpecial();

where replaceSpecial() will automatically replace say, the letter e with something else.

The reason I'm interested in doing this is because what I want to do is grab strings and then run a large number of replace actions, so I'm hoping that when I call on replaceSpecial() it will run a function.

Thanks

like image 504
Pete Avatar asked Feb 03 '26 05:02

Pete


1 Answers

You can add your methods to String.prototype which will become available to all strings. That is how trim() is implemented in most libraries for example.

String.prototype.replaceSpecial = function() {
    return this.replace(/l/g, 'L');
};

"hello".replaceSpecial(); // heLLo

However, note that it is generally a bad practice to define very specific functionality on the native prototypes. The above is a good example of exactly the same problem. For such specific cases, consider using a custom function or wrapper to do the job.

function replaceSpecial(str) {
    return str.replace(/l/g, 'L');
}

replaceSpecial("hello"); // heLLo

or under a custom namespace, for example.

var StringUtils = {
    replaceSpecial: function(str) { .. },
    ..
};

StringUtils.replaceSpecial("hello"); // heLLo
like image 174
Anurag Avatar answered Feb 05 '26 21:02

Anurag