string-format是一个小型的JavaScript库,用于基于Python的格式化字符串str.format()
第一个参数是模板字符串,其余参数是要插值的值
demo:
format('Hello, {}!', 'Alice')
// => 'Hello, Alice!'
⬇️
'Hello, {}!'.format('Alice')
// => 'Hello, Alice!'
//返回将{…}模板字符串中的每个占位符替换为其对应替换的结果。
format(template, $0, $1, …, $N)
demo:
//占位符可以包含引用位置参数的数字
'{0}, you have {1} unread message{2}'.format('Holly', 2, 's')
// => 'Holly, you have 2 unread messages'
//占位符不产生任何输出
'{0}, you have {1} unread message{2}'.format('Steve', 1)
// => 'Steve, you have 1 unread message'
//格式字符串可以多次引用位置参数:
"The name's {1}. {0} {1}.".format('James', 'Bond')
// => "The name's Bond. James Bond."
//位置参数可以隐式引用:
'{}, you have {} unread message{}'.format('Steve', 1)
// => 'Steve, you have 1 unread message'
//格式字符串不能同时包含隐式和显式引用:
'My name is {} {}. Do you like the name {0}?'.format('Lemony', 'Snicket')
// => ValueError:无法从隐式编号切换为显式编号
//{{}}以格式字符串产生{}:
'{{}} creates an empty {} in {}'.format('dictionary', 'Python')
// => '{} creates an empty dictionary in Python'
更多用法参考来源