javascript - Python 的 %s 在 Javascript 中的等价物?
问题描述
在过去几年使用 Python 之后,我目前正在学习 NodeJS。
在 Python 中,我能够使用动态参数将字符串保存在 JSON 中,并在加载字符串后设置它们,例如:
我的 JSON:
j = {
"dynamicText": "Hello %s, how are you?"
}
然后像这样使用我的字符串:
print(j['dynamicText'] % ("Dan"))
所以 Python 用%s
“ Dan
”替换了。
我正在寻找等效的 JS,但找不到。有任何想法吗?
** 忘了提:我想将 JSON 保存为另一个配置文件,所以文字在这里不起作用
解决方案
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"
希望这可以帮助。
推荐阅读
- vue.js - 如何将 D3 组件附加到另一个 vue 文件中的 div
- eclipse - 每次都有 java.lang.NullPointerException
- node.js - ng-selected 不起作用,但将选项修改为 selected="selected",使用 ng-repeat
- css - SCSS/CSS 不使用 webpack 加载
- shiny - 在任何情况下我都无法使用 mathjax
- javascript - react-select 错误:str.replace 不是函数错误
- puppeteer - 用户界面在 puppeteer 上似乎有所不同
- unit-testing - 使用 Mockito 检查方法是否被不同的值调用
- java - 不需要新变量声明的小函数的可读性
- spring-security - SSHA512 加密并与 spring 5 匹配