使用反引号 `
创建的字符串可以包含表达式,这些表达式会被相应的值替换。
let name = 'Alice';
let age = 30;
let str = `My name is ${name} and I am ${age} years old.`;
// 结果: "My name is Alice and I am 30 years old."
字符串连接:
let name = 'Alice';
let age = 30;
let str = 'My name is ' + name + ' and I am ' + age + ' years old.';
// 结果: "My name is Alice and I am 30 years old."
let template = 'My name is %name% and I am %age% years old.';
let str = template.replace('%name%', 'Alice').replace('%age%', 30);
// 结果: "My name is Alice and I am 30 years old."
Intl
和 Number.prototype.toLocaleString
方法:
对于更复杂的数字和日期格式化,你可以使用 Intl
对象和相关方法。
let number = 12345.67;
let formattedNumber = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
// 结果: "$12,345.67"
使用模板字面量是最现代和灵活的方法,它允许你在字符串中直接插入表达式和变量。
原文地址:https://blog.csdn.net/m0_57236802/article/details/132287295
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_15223.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!