首页 > 解决方案 > Python 的 %s 在 Javascript 中的等价物?

问题描述

在过去几年使用 Python 之后,我目前正在学习 NodeJS。

在 Python 中,我能够使用动态参数将字符串保存在 JSON 中,并在加载字符串后设置它们,例如:

我的 JSON:

j = {
"dynamicText": "Hello %s, how are you?"
}

然后像这样使用我的字符串:

print(j['dynamicText'] % ("Dan"))

所以 Python 用%sDan”替换了。

我正在寻找等效的 JS,但找不到。有任何想法吗?

** 忘了提:我想将 JSON 保存为另一个配置文件,所以文字在这里不起作用

标签: javascriptnode.js

解决方案


JavaScript 中没有预定义的方法,但您仍然可以实现如下所示的内容。我在现有应用程序中所做的。

function formatString(str, ...params) {
    for (let i = 0; i < params.length; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        str = str.replace(reg, params[i]);
    }
    return str;
}

现在formatString('You have {0} cars and {1} bikes', 'two', 'three')返回'You have two cars and three bikes'

这样,如果 {0} 在 String 中重复,它将全部替换。

喜欢formatString('You have {0} cars, {1} bikes and {0} jeeps', 'two', 'three')_"You have two cars, three bikes and two jeeps"

希望这可以帮助。


推荐阅读