8

I'm migrating from Aura component into LWC component.

Trying to find a standard replacement statement in lwc to replace custom labels tokens with dynamic values.

Custom Label Value:

"Range Between {0} to {1}"

in Aura I could do :

{!format($Label.c.MyCustomLabel, v.value1,v.value2)}

How should I do it in lwc?

16

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.