averainy's Blog

averainy

06 Dec 2023

Implementing String Format Method with TypeScript

Implementing String Format Method with TypeScript

const format = (msg: string, parames?: Object): string => {
    if (!parames) {
        return msg;
    }
    (Object.keys(parames) as (keyof typeof parames)[]).forEach((key, index) => {
        const regExp = new RegExp(`\\{${key}\\}`, 'g');
        msg = msg.replace(regExp, parames[key] as unknown as string);
    });

    return msg;
}

let msg = "{0} {1}";
const params = {
    '0': "hello",
    '1': "world"
}
console.log(format(msg, params));

Categories