Custom replace method?
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开发者_Go百科
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
精彩评论