Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中插入字符串中的变量,而无需连接?_Javascript_String_Variables_String Interpolation - Fatal编程技术网

如何在JavaScript中插入字符串中的变量,而无需连接?

如何在JavaScript中插入字符串中的变量,而无需连接?,javascript,string,variables,string-interpolation,Javascript,String,Variables,String Interpolation,我知道,在PHP中,我们可以执行以下操作: $hello = "foo"; $my_string = "I pity the $hello"; String.prototype.create = function(o) { return Strings.create(this, o); } 输出:“我可怜这家伙” String.prototype.create = function(o) { return Strings.create(this,

我知道,在PHP中,我们可以执行以下操作:

$hello = "foo";
$my_string = "I pity the $hello";
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
输出:
“我可怜这家伙”

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
我想知道同样的事情在JavaScript中是否也可能发生。在字符串中使用变量而不使用串联 — 写起来更简洁优雅。

Firefox34/Chrome 41/Safari 9/Microsoft Edge,不,这在javascript中是不可能的。你必须求助于:

var hello = "foo";
var my_string = "I pity the " + hello;
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
Firefox 34/Chrome 41/Safari 9/Microsoft Edge,没有。尽管你可以尝试半途而废:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
String.prototype.create = function(o) {
           return Strings.create(this, o);
}

如果您试图为微模板制作插值,我喜欢这样做。

您可以这样做,但它不是通用的

'I pity the $fool'.replace('$fool', 'fool')
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
如果确实需要,您可以轻松编写一个智能化的函数,您可以利用并使用以下语法:

`String text ${expression}`
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
模板文本由反勾(``)(严重重音)括起,而不是双引号或单引号

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
此功能已在ES2015(ES6)中引入

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

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
那有多整洁

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

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
它还允许在javascript中使用多行字符串,而无需转义,这对于模板非常有用:

return `
    <div class="${foo}">
         ...
    </div>
`;
String.prototype.create = function(o) {
           return Strings.create(this, o);
}

如果你喜欢写咖啡脚本,你可以:

hello = "foo"
my_string = "I pity the #{hello}"
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
CoffeeScript实际上是javascript,但具有更好的语法

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

有关CoffeeScript的概述,请检查此项。

您可以使用此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"
    }
);
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
输出
“我想收到来自该商店FOO BAR BAZ的电子邮件更新。”

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

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

完整答案,准备使用:

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

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
称为

Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
String.prototype.create = function(o) {
           return Strings.create(this, o);
}
要将其附加到String.prototype,请执行以下操作:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
然后用作:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
"My firstname is ${first}".create({first:'Neo'});

我编写了这个npm包stringinject,它允许您执行以下操作

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
它将用数组项替换{0}和{1},并返回以下字符串

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
"this is a test string for stringInject"
也可以使用对象键和值替换占位符,如下所示:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 

这里没有提到任何外部库,但Lodash有
\uuu0.template()

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

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
如果您已经使用了该库,那么值得一看,如果您没有使用Lodash,您可以从npm
npm install Lodash.template
中挑选方法,这样您就可以减少开销

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
最简形式-

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'
我发现自定义分隔符最有趣

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
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:

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

我会用后面的勾号“`”

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
let name1='Geoffrey';
让msg1=`Hello${name1}`;
console.log(msg1);/'你好,杰弗里的朋友
但是如果您在创建
msg1
时不知道
name1

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
例如,如果
msg1
来自API

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
您可以使用:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
let name2='Geoffrey';
让msg2='Hello${name2}';
console.log(msg2);/'你好${name2}'
常量regexp=/\${([^{]+)}/g;
让result=msg2.replace(regexp,函数(ignore,key){
返回eval(键);
});
console.log(结果);//“你好,杰弗里”
它将用他的值替换
${name2}

var hello=“foo”

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

log(my_string,hello)

创建一个类似于Java的
string.format()
的方法

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}
使用

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
2020年和平宣言:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}
Console.WriteLine("I {0} JavaScript!", ">:D<");

console.log(`I ${'>:D<'} C#`)
Console.WriteLine(“I{0}JavaScript!”,“>:D只需使用:

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

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

谢谢。如果您使用的是dojo,sprintf可以作为一个模块使用:它很快就可以在javascript(ES6)中使用模板字符串,请参阅下面我的详细答案。如果您喜欢编写CoffeeScript,它实际上是具有更好语法的javascript。对于较旧的浏览器来说,这是一个好消息:)不要错过这样一个事实:模板字符串是用回号(`)而不是普通的引号字符分隔的。
“${foo}”
是字面上的${foo}
“${foo}`
是您真正想要的,所以有许多Transpiler可以将ES6转换为ES5来修复兼容性问题!当我更改a或b值时。console.log(
15是${a+b}.
);不会动态更改。它总是显示15是15。回勾是生命的救星。但问题是,当我在php文件中使用时,$变量将被视为php变量,而不是js变量,因为php变量的格式为$variable_name。这是否有效?效率将主要取决于用户的浏览器,因为is解决方案将匹配正则表达式和替换字符串的“繁重任务”委托给浏览器的本机函数。无论如何,由于这都是在浏览器端进行的,所以效率并不是一个大问题。如果您想要服务器端模板(对于Node.JS或类似的)您应该使用@bformet所描述的ES6模板文本解决方案,因为它可能更有效。实际上,相当不错。当您需要在数据库中存储模板字符串并按需处理时,这个答案很好。很好,它工作得很好。很简单,但没有想到。这并不能回答问题。您可以同时注销两个字符串在一行中,但这不会给您一个包含两个字符串的新字符串,这是OP所要求的。