Owen Kelvin
Owen Kelvin

Reputation: 15083

String with a variable that can be replaced (php's sprintf equivalent)

I have a class that looks like below

interface IParams: {
  academicYearId: number;
  // Other Params
};
export class myClass() {
  function1() {
    const url = `api/accounts/academic-year/${academicYearId}/financial-plan`;
    // Function 1 Functionality
  }
  function2() {
    const url = `api/accounts/academic-year/${academicYearId}/financial-plan`;
    // Function 2 Functionality
  }
  function3() {
    const url = `api/accounts/academic-year/${academicYearId}/financial-plan`;
    // Function 2 Functionality
  }
}

To reduce on the repetition I made url a property

interface IParams: {
  academicYearId: number;
  // Other Params
};
export class myClass({academicYearId}: ) {
  url = `api/accounts/academic-year/:id/financial-plan`;
  urlWithId = (academicYearId: number) => this.url.replace(':id', academicYearId )
  function1() {
    const url = this.urlWithId(academicYearId)
    // Function 1 Functionality
  }
  function2() {
    const url = this.urlWithId(academicYearId)
    // Function 2 Functionality
  }
  function3() {
    const url = this.urlWithId(academicYearId)
    // Function 2 Functionality
  }
}

The above approach works but am I was wondering if there is a better way I can approach the below two lines other than setting a part of the string to ':id' and then replace that part with the id value. Something like in php's sprintf

url = `api/accounts/academic-year/:id/financial-plan`;
urlWithId = (academicYearId: number) => this.url.replace(':id', academicYearId )

Upvotes: 0

Views: 171

Answers (1)

Ali Soltani
Ali Soltani

Reputation: 9937

String interpolation

It's a common approach for doing that like below:

urlWithId = (academicYearId) => `api/accounts/academic-year/${academicYearId}/financial-plan`;

Upvotes: 2

Related Questions