Custom replacement method?

Is it possible to create your own user, I believe the term "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 this is because what I want to do is grab the strings and then start a lot of replacement actions, so I hope that when I call replaceSpecial (), it will run the function.

thank

+3
source share
1 answer

You can add your methods to String.prototype, which will be available for all lines. This is how it trim()is implemented in most libraries, for example.

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

"hello".replaceSpecial(); // heLLo

, , , , . . .

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

replaceSpecial("hello"); // heLLo

, .

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

StringUtils.replaceSpecial("hello"); // heLLo
+8

Source: https://habr.com/ru/post/1756376/


All Articles