Currently, there is no native solution for replacing custom labels tokens with dynamic values in LWC. But you can implement similar functionality using pure js.
Let's create some service LWC component IntlService
to be able to reuse its functionality from everywhere:
class IntlService {
static format(stringToFormat, ...formattingArguments) {
if (typeof stringToFormat !== 'string') throw new Error('\'stringToFormat\' must be a String');
return stringToFormat.replace(/{(\d+)}/gm, (match, index) =>
(formattingArguments[index] === undefined ? '' : `${formattingArguments[index]}`));
}
}
export { IntlService };
So now, we can import this module into our LWC component and all the features of this module are now at our disposal:
<template>
{label}
</template>
import { LightningElement } from 'lwc';
import Placeholder from '@salesforce/label/c.Placeholder'; /*{0} lives in {1}.*/
import { IntlService } from 'c/intlService';
export default class Component extends LightningElement {
firstName = 'Jim';
city = 'London';
get label() {
return IntlService.format(Placeholder, this.firstName, this.city);
}
}
Result:
Jim lives in London.
In this case, all the magic is performed by the String.prototype.replace()
method which returns a new string with some or all matches of a pattern
replaced by a replacement
. The pattern
can be a string
or a RegExp
, and the replacement
can be a string
or a function
to be called for each match.