如何在JavaScript中进行字符串插值?

JavaScript

梅Near米亚

2020-03-12

考虑以下代码:

var age = 3;

console.log("I'm " + age + " years old!");

除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?

第1198篇《如何在JavaScript中进行字符串插值?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
蛋蛋神乐 2020.03.12

找不到我想要的东西,然后找到了-

如果您使用的是Node.js,则有一个内置的util软件包,其格式函数如下所示:

util.format("Hello my name is %s", "Brent");
> Hello my name is Brent

巧合的是console.log,Node.js 现在也将其内置于风味中-

console.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError
小小村村 2020.03.12

这是一个解决方案,要求您为对象提供值。如果不提供对象作为参数,则默认使用全局变量。但是最好还是坚持使用参数,因为它要干净得多。

String.prototype.interpolate = function(props) {
    return this.replace(/\{(\w+)\}/g, function(match, expr) {
        return (props || window)[expr];
    });
};

// Test:

// Using the parameter (advised approach)
document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 });

// Using the global scope
var eruption2 = 116;
document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate();
<div id="resultA"></div><div id="resultB"></div>

斯丁前端 2020.03.12

如果要在console.log输出中进行插值,则只需

console.log("Eruption 1: %s", eruption1);
                         ^^

在这里,%s就是所谓的“格式说明符”。console.log具有内置的这种插值支持。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android