如何在 JavaScript 中插入字符串中的变量而不使用连接?

发布于 2024-09-10 17:00:41 字数 221 浏览 2 评论 0原文

我知道在 PHP 中我们可以做这样的事情:

$hello = "foo";
$my_string = "I pity the $hello";

Output: "I pity the foo"

我想知道在 JavaScript 中是否也可以做同样的事情。在字符串中使用变量而不使用连接——看起来写起来更加简洁和优雅。

I know in PHP we can do something like this:

$hello = "foo";
$my_string = "I pity the $hello";

Output: "I pity the foo"

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

小嗲 2024-09-17 17:00:41

您可以利用模板文字并使用此语法:

`String text ${expression}`

模板文字用反引号 (` `)(重音符号)括起来,而不是双引号或单引号。

该功能已在 ES2015(ES6)中引入。

示例

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.

这有多简洁?

奖励:

它还允许在 javascript 中使用多行字符串而无需转义,这对于模板来说非常有用:

return `
    <div class="${foo}">
         ...
    </div>
`;

浏览器支持

由于旧版浏览器(主要是 Internet Explorer)不支持此语法,您可能需要使用 Babel/Webpack 将您的代码转换为 ES5,以确保它可以在任何地方运行。


旁注:

从 IE8+ 开始,您可以在 console.log 中使用基本字符串格式:

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.

You can take advantage of Template Literals and use this syntax:

`String text ${expression}`

Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.

This feature has been introduced in ES2015 (ES6).

Example

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.

How neat is that?

Bonus:

It also allows for multi-line strings in javascript without escaping, which is great for templates:

return `
    <div class="${foo}">
         ...
    </div>
`;

Browser support:

As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.


Side note:

Starting from IE8+ you can use basic string formatting inside console.log:

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
┼── 2024-09-17 17:00:41

之前的 Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge,不,这在 javascript 中是不可能的。您将不得不求助于:

var hello = "foo";
var my_string = "I pity the " + hello;

Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, nope, that was not possible in javascript. You would have to resort to:

var hello = "foo";
var my_string = "I pity the " + hello;
诗化ㄋ丶相逢 2024-09-17 17:00:41

Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge 之前,没有。尽管您可以尝试 sprintf for JavaScript 来达到目的:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);

Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
若能看破又如何 2024-09-17 17:00:41

好吧,你可以做到这一点,但这不是特别普遍的,

'I pity the $fool'.replace('$fool', 'fool')

如果你真的需要的话,你可以轻松地编写一个智能地执行此操作的函数

well you could do this, but it's not esp general

'I pity the $fool'.replace('$fool', 'fool')

You could easily write a function that does this intelligently if you really needed to

ゃ懵逼小萝莉 2024-09-17 17:00:41

如果缺少 ES6,则完成并准备使用答案:

 var Strings = {
        create : (function() {
                var regexp = /#{([^{]+)}/g;

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};

调用 as

Strings.create("My firstname is #{first}, my last name is #{last}", {first:'Neo', last:'Andersson'});

将其附加到 String.prototype

String.prototype.create = function(o) {
           return Strings.create(this, o);
}

然后使用 as :

"My firstname is #{first}".create({first:'Neo'});

如果您使用 >ES6< /strong> 那么你也可以这样做:

let first = 'Neo'; 
`My firstname is ${first}`; 

Complete and ready to be used answer if lacking ES6:

 var Strings = {
        create : (function() {
                var regexp = /#{([^{]+)}/g;

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};

Call as

Strings.create("My firstname is #{first}, my last name is #{last}", {first:'Neo', last:'Andersson'});

To attach it to String.prototype:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}

Then use as :

"My firstname is #{first}".create({first:'Neo'});

If you are on >ES6 then you can also do:

let first = 'Neo'; 
`My firstname is ${first}`; 
心是晴朗的。 2024-09-17 17:00:41

2022 更新:只需使用 ES6 模板文字功能几乎所有您现在遇到的浏览器都完全支持它。如果您仍然以 IE11 及更低版本等浏览器为目标……那么,我很同情您。我 5 年前提出的以下解决方案仍然适用于您。另外,如果您想要一份不涉及旧浏览器的工作,请给我发电子邮件。

您可以使用此 javascript 函数来执行此类模板化。无需包含整个库。

function createStringFromTemplate(template, variables) {
    return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
        return variables[varName];
    });
}

createStringFromTemplate(
    "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
    {
        list_name : "this store",
        var1      : "FOO",
        var2      : "BAR",
        var3      : "BAZ"
    }
);

输出“我想从这家商店接收电子邮件更新 FOO BAR BAZ。”

使用函数作为 String.replace() 函数的参数是ECMAScript v3 规范。有关更多信息,请参阅这个答案细节。

2022 update: Just use the ES6 Template Literals feature. It's fully supported in practically every browser you'll encounter these days. If you are still targeting browsers like IE11 and lower .. well, my heart goes out to you. The below solution I came up with 5 years ago will still work for you. Also, email me if you want a job that doesn't involve catering to old browsers ????.

You can use this javascript function to do this sort of templating. No need to include an entire library.

function createStringFromTemplate(template, variables) {
    return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
        return variables[varName];
    });
}

createStringFromTemplate(
    "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
    {
        list_name : "this store",
        var1      : "FOO",
        var2      : "BAR",
        var3      : "BAZ"
    }
);

Output: "I would like to receive email updates from this store FOO BAR BAZ."

Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.

み零 2024-09-17 17:00:41

如果您喜欢编写 CoffeeScript,您可以这样做:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript 实际上是 javascript,但具有更好的语法。

有关 CoffeeScript 的概述,请查看此初学者指南

If you like to write CoffeeScript you could do:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript actually IS javascript, but with a much better syntax.

For an overview of CoffeeScript check this beginner's guide.

撩心不撩汉 2024-09-17 17:00:41

我会使用反引号``。

let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'

但如果您在创建 msg1 时不知道 name1

例如,如果 msg1 来自 API。

您可以使用:

let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'

const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
    return eval(key);
});
console.log(result); // 'Hello Geoffrey'

它将用他的值替换 ${name2}

I would use the back-tick ``.

let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'

But if you don't know name1 when you create msg1.

For exemple if msg1 came from an API.

You can use :

let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'

const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
    return eval(key);
});
console.log(result); // 'Hello Geoffrey'

It will replace ${name2} with his value.

栖迟 2024-09-17 17:00:41

我写了这个 npm 包 stringinject https://www.npmjs.com/package/stringinject 它允许您可以执行以下操作

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

,将 {0} 和 {1} 替换为数组项并返回以下字符串

"this is a test string for stringInject"

,或者您可以将占位符替换为对象键和值,如下所示:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 

I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

which will replace the {0} and {1} with the array items and return the following string

"this is a test string for stringInject"

or you could replace placeholders with object keys and values like so:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 
双马尾 2024-09-17 17:00:41

如果您尝试对微模板进行插值,我喜欢 Mustache.js 来实现此目的。

If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.

沙与沫 2024-09-17 17:00:41

没有看到这里提到的任何外部库,但 Lodash 有 _.template(),

https://lodash.com/docs/4.17.10#template

如果您已经在使用该库,那么值得一试,如果您没有使用 Lodash,您可以始终从 npm npm install lodash.template 中挑选方法,这样您就可以减少开销。

最简单的形式 -

var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'

还有很多配置选项 -

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'

我发现自定义分隔符最有趣。

Don't see any external libraries mentioned here, but Lodash has _.template(),

https://lodash.com/docs/4.17.10#template

If you're already making use of the library it's worth checking out, and if you're not making use of Lodash you can always cherry pick methods from npm npm install lodash.template so you can cut down overhead.

Simplest form -

var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'

There are a bunch of configuration options also -

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'

I found custom delimiters most interesting.

谁的年少不轻狂 2024-09-17 17:00:41

只需使用:

var util = require('util');

var value = 15;
var s = util.format("The variable value is: %s", value)

Simply use:

var util = require('util');

var value = 15;
var s = util.format("The variable value is: %s", value)
把回忆走一遍 2024-09-17 17:00:41

String.format()的方法

StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}

创建类似于Java使用

console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'

Create a method similar to String.format() of Java

StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}

use

console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
番薯 2024-09-17 17:00:41

2020年和平报价:

Console.WriteLine("I {0} JavaScript!", ">:D<");

console.log(`I ${'>:D<'} C#`)

Peace quote of 2020:

Console.WriteLine("I {0} JavaScript!", ">:D<");

console.log(`I ${'>:D<'} C#`)
墨落画卷 2024-09-17 17:00:41

或许

wrt=(s, arr=[])=>{
    arr.map((v,i)=>{s = s.replace(/\?/,v);});
    return s;
};
a='first var';
b='secondvar';
tr=wrt('<tr><td>?<td></td>?</td><tr>',[a,b]);
console.log(tr);
//or use tr in html(tr), append(tr) so on and so forth
// Use ? with care in s

Maybe

wrt=(s, arr=[])=>{
    arr.map((v,i)=>{s = s.replace(/\?/,v);});
    return s;
};
a='first var';
b='secondvar';
tr=wrt('<tr><td>?<td></td>?</td><tr>',[a,b]);
console.log(tr);
//or use tr in html(tr), append(tr) so on and so forth
// Use ? with care in s
你穿错了嫁妆 2024-09-17 17:00:41
let data = Hello User
console.log(`<a href=''><i class='fa-solid fa-star'></i>${data}</a>`)

输出=> 您好用户

注意
使用 `` 不要使用 "" 或 '' 它不会起作用

let data = Hello User
console.log(`<a href=''><i class='fa-solid fa-star'></i>${data}</a>`)

output => <a href=''><i class='fa-solid fa-star'></i>Hello User</a>

note
use `` don't use "" or '' it will not work

若相惜即相离 2024-09-17 17:00:41
String.prototype.interpole = function () {
    var c=0, txt=this;
    while (txt.search(/{var}/g) > 0){
        txt = txt.replace(/{var}/, arguments[c]);
        c++;
    }
    return txt;
}

乌索:

var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
String.prototype.interpole = function () {
    var c=0, txt=this;
    while (txt.search(/{var}/g) > 0){
        txt = txt.replace(/{var}/, arguments[c]);
        c++;
    }
    return txt;
}

Uso:

var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
静若繁花 2024-09-17 17:00:41

var hello = "foo";

var my_string ="I pity the";

console.log(my_string, 你好)

var hello = "foo";

var my_string ="I pity the";

console.log(my_string, hello)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文