Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
JS, how to access to "this" in a replacer function in a call to String.prototype.replace()

I have this piece of code:

class MyClass {
  constructor(text, pattern) {
    this.text = text;
    this.pattern = pattern;
  }

  run() {
    return this.text.replace(/(\d)/, this.replacer)
  }

  replacer(match, timeString, offset, string) {
    return this.pattern;
  }
}

It is a simplified example of my actual code.

When I run:

var v = new MyClass("text 1 2", "X");
v.run();

I see the error:

Uncaught TypeError: Cannot read properties of undefined (reading 'pattern')

How can access to this in this replacer function?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use Function#bind to set the this value, or use an arrow function that calls this.replacer as the callback.

class MyClass {
  constructor(text, pattern) {
    this.text = text;
    this.pattern = pattern;
  }

  run() {
    return this.text.replace(/(\d)/, this.replacer.bind(this));
    // or return this.text.replace(/(\d)/, (...args) => this.replacer(...args));
  }

  replacer(match, timeString, offset, string) {
    return this.pattern;
  }
}
var v = new MyClass("text 1 2", "X")
console.log(v.run());

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!