ChatGPT解决这个技术问题 Extra ChatGPT

如何在不连接的情况下在 JavaScript 中的字符串中插入变量?

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

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

输出:"I pity the foo"

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


b
bformet

您可以利用 Template Literals 并使用以下语法:

`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>
`;

Browser support

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

边注:

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

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

不要错过模板字符串用反引号 (`) 而不是正常的引号字符分隔的事实。 "${foo}" 字面意思是 ${foo} `${foo}` 是你真正想要的
还有很多转译器将 ES6 转为 ES5 以修复兼容性问题!
当我更改 a 或 b 值时。控制台.log(Fifteen is ${a + b}.);不会动态改变。它总是显示 15 是 15。
背蜱是生命的救星。
但问题是当我在 php 文件中使用它时,$variable 将被视为 php 变量而不是 js 变量,因为 php 变量的格式为 $variable_name。
C
Community

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

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

很快就可以在带有模板字符串的 javascript (ES6) 中使用,请参阅下面的详细答案。
It is possible 如果您喜欢编写 CoffeeScript,它实际上是语法更好的 javascript。
对旧浏览器大喊大叫:)
C
Community

Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge,没有。尽管您可以尝试 sprintf for JavaScript 以达到一半:

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

谢谢。如果您使用的是 dojo,则 sprintf 可作为模块使用:bill.dojotoolkit.org/api/1.9/dojox/string/sprintf
S
Scott Evernden

好吧,您可以这样做,但这不是一般的

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

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


相当不错,其实。
当您需要将模板字符串存储在数据库中并按需处理时,此答案很好
好一个,效果很好。很简单,但没有想到。
m
mjs

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

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

调用为

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);
}

然后用作:

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

如果您在 >ES6 上,那么您还可以执行以下操作:

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

E
Eric Seastrand

你可以使用这个 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"
    }
);

输出"I would like to receive email updates from this store FOO BAR BAZ."

使用函数作为 String.replace() 函数的参数是 ECMAScript v3 规范的一部分。有关详细信息,请参阅 this SO answer


这有效率吗?
效率很大程度上取决于用户的浏览器,因为该解决方案将匹配正则表达式和进行字符串替换的“繁重工作”委托给浏览器的本机函数。无论如何,由于这无论如何都发生在浏览器端,因此效率并不是一个大问题。如果您想要服务器端模板(对于 Node.JS 等),您应该使用 @bformet 描述的 ES6 模板文字解决方案,因为它可能更有效。
b
bformet

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

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

CoffeeScript 实际上是 javascript,但语法要好得多。

有关 CoffeeScript 的概述,请查看此 beginner's guide


g
gturquais

我会使用反勾号``。

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}


t
tjcafferkey

我编写了这个 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" 

J
Joe Martinez

如果您尝试为微模板进行插值,我喜欢 Mustache.js 用于此目的。


M
Mark Carpenter Jr

看不到这里提到的任何外部库,但 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!'

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


F
Federico Caccia

只需使用:

var util = require('util');

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

A
Abran Salas Molina
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"

E
Emerson Barcellos

创建类似于Java的String.format()的方法

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

利用

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

M
MatrixRonny

2020年和平报价:

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

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

l
lalithya

var hello = "foo";

var my_string ="I pity the";

控制台日志(我的字符串,你好)


那没有回答问题。您可以在一行中注销两个字符串,但这不会为您提供包含两个字符串的新字符串,这是 OP 所要求的。