可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
Starting from Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge you can use an ES2015 / ES6 feature called 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.
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 (Internet Explorer and Safari <= 8), you may want to use Babel 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.
回答2:
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;
回答3:
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);
回答4:
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
回答5:
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.
回答6:
Complete answer, ready to be used:
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\'});
回答7:
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.
回答8:
If you\'re trying to do interpolation for microtemplating, I like Mustache.js for that purpose.
回答9:
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\"
回答10:
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.