string-format的用法

373 阅读1分钟
import format from 'string-format';
//可以在两种模式下使用: function mode(功能模式) and method mode(方法模式).

const MES='Hello, {}!'

//功能模式
format(MES, 'Alice')
console.dir(format(MES, 'Alice'))  //  'Hello,Alice'

//方法模式
MES.format('Alice')
console.dir(MES.format('Alice'))  //  'Hello,Alice'

//返回将{…}模板字符串中的每个占位符替换为其对应替换的结果。
format(template, $0, $1, …, $N)

const MES1='{0}, you have {1} unread message{2}'

//占位符可以包含引用位置参数的数字:
MES1.format('Holly', 2, 's')
console.dir(MES1.format('Holly', 2, 's'))  //'Holly, you have 2 unread messages'

//未匹配的占位符不产生任何输出:
MES1.format('Steve', 1)
console.dir(MES1.format('Steve', 1)) //'Steve, you have 1 unread message'

//格式字符串可以多次引用位置参数:
"The name's {1}. {0} {1}.".format('James', 'Bond')
// => "The name's Bond. James Bond."

/*隐式引用 不标识index*/

//位置参数可以隐式引用:
'{}, 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: cannot switch from implicit to explicit numbering

//{{}}以格式字符串产生{}:
'{{}} creates an empty {} in {}'.format('dictionary', 'Python')
// => '{} creates an empty dictionary in Python'

//点符号可用于引用对象属性:
const bobby = {firstName: 'Bobby', lastName: 'Fischer'}
const garry = {firstName: 'Garry', lastName: 'Kasparov'}
 
'{0.firstName} {0.lastName} vs. {1.firstName} {1.lastName}'.format(bobby, garry)
// => 'Bobby Fischer vs. Garry Kasparov'

更多使用请参考来源链接!

来源链接:www.npmjs.com/package/str…