You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js环境下实现可变参数占位符替换构造自定义错误消息

Node.js 可变参数占位符消息构造工具实现方案

核心实现思路:通过正则全局匹配$N格式的占位符,将匹配到的数字下标减1后对应参数数组的取值完成替换。

完整模块实现代码

const licenseNotificationMessages = {
    CapacityAlmostExpired:{
        description: 'my description contains $1 followed by $2 followed by $3 in this case.',
    },
    CapacityExpired:{
       description: 'my description contains $1 followed by $2 in this case.',
    },
}

/**
 * 替换消息模板中的$1、$2...$N占位符为对应参数
 * @param {string} message 消息模板字符串
 * @param {Array} args 占位符对应的值数组
 * @returns {string} 替换完成的最终消息
 */
const constructMessage = (message, args) => {
    // 正则匹配所有$开头加数字的占位符
    return message.replace(/\$(\d+)/g, (match, index) => {
        // 占位符$1对应数组下标0,所以减1
        const value = args[Number(index) - 1];
        // 若对应参数不存在可自定义返回逻辑,这里默认返回空字符串,也可保留原占位符返回match
        return value !== undefined ? value : '';
    });
}

module.exports = {
    licenseNotificationMessages,
    constructMessage,
}

调用示例说明

注意:你提供的调用示例中存在写法错误,constructMessage是顶层导出的方法,不属于licenseNotificationMessages对象,正确调用方式如下:

const { licenseNotificationMessages, constructMessage } = require('./licenseNotificationMessages');

// 测试CapacityAlmostExpired模板
const desc1 = constructMessage(
    licenseNotificationMessages.CapacityAlmostExpired.description, 
    ['val_for_$1', 'val_for_$2', 'val_for_$3']
);
// 输出结果:my description contains val_for_$1 followed by val_for_$2 followed by val_for_$3 in this case.

// 测试CapacityExpired模板
const desc2 = constructMessage(
    licenseNotificationMessages.CapacityExpired.description, 
    ['val_for_$1', 'val_for_$2']
);
// 输出结果:my description contains val_for_$1 followed by val_for_$2 in this case.

兼容多参数传入的扩展实现

如果你想支持constructMessage(tpl, val1, val2, val3)这种逐个传参的写法,可以调整方法实现如下:

const constructMessage = (message, ...args) => {
    // 兼容第一个参数是数组的情况,适配你原来的调用习惯
    const actualArgs = Array.isArray(args[0]) ? args[0] : args;
    return message.replace(/\$(\d+)/g, (match, index) => {
        const value = actualArgs[Number(index) - 1];
        return value !== undefined ? value : '';
    });
}

调整后两种调用方式都可以正常使用:

// 传数组
constructMessage(tpl, ['a','b','c'])
// 逐个传参
constructMessage(tpl, 'a','b','c')

内容的提问来源于stack exchange,提问作者Pradip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:06:03