Recently I was looking for ways to remove / replace a substring in JS. I came across this example of the custom removal function:

String.prototype.removeWord = function(searchWord){ var str = this; var n = str.search(searchWord); while(str.search(searchWord) > -1){ n = str.search(searchWord); str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length); } return str; 

Because I started studying JS recently, I had a question: what happens in the string

var str = this;

Why do we need this kind of assignment and what does it actually put in the variable str ? Thank.

  • can be not appropriated - Grundy

2 answers 2

This assignment places in the str variable a reference to the string whose method is being executed. This sets the initial value of the string that changes in the iterative deletion process.

    In this case, this kind of assignment can be done in order to reduce the amount of code, or in order not to change this value.

    In other cases, such an assignment inside a function is done for a closure, which is written here .