Reputation: 1
Here is a demo which was written by Scott Allen:
var x = 1;
var y = 3;
var upper = function (string, ...values) {
var result = '';
for (let i = 0; i < string.length; i++) {
result += string[i];
if (i < values.length) {
result += values[i]
}
}
console.log('string', string)
console.log('values', values)
return result.toUpperCase()
};
var result = upper `${x} + ${y} is ${x + y}`
console.log(result)
My question: How does javascript detect array string and array values via
${x} + ${y} is ${x + y}
?
Is it: split ${x} + ${y} is ${x + y}
and select the parts which are outside ${}
?
And second question: I've wrapped ${x} + ${y} is ${x + y}
by ()
, string
and values
were changed but same result like the first example. Is it right syntax? Or should I avoid using ()
in this case?
var x = 1;
var y = 3;
var upper = function (string, ...values) {
var result = '';
for (let i = 0; i < string.length; i++) {
result += string[i];
if (i < values.length) {
result += values[i]
}
}
console.log('string', string)
console.log('values', values)
return result.toUpperCase()
};
var result = upper (`${x} + ${y} is ${x + y}`)
console.log(result)
p/s: I've searched in Google Search with keywords javascript template but no document mentioned about it.
Upvotes: 1
Views: 97
Reputation: 21887
This is a new feature in ECMAScript 2015 known as a template literal. It is a string delimited by backticks, which can contain JavaScript expressions within it. Normally, these expressions are evaluated and then interpolated into the string. However, by specifying a function name directly before the template literal, you can use that function to create a custom result. For example:
var name = "Bob";
`Hello, ${name}!`
// prints "Hello, Bob!"
function ignoreValues(strings, values) {
// strings is array of original string, split at ${} points
// values is array of evaluated result of expressions within ${}
// both arrays are in order, so you can go back and forth between their elements
return strings.join('');
}
ignoreValues`Hello, ${name}!`
// prints "Hello, !"
See documentation.
Upvotes: 1
Reputation: 1
p/s: I've searched in Google Search with keywords javascript template but no document mentioned about it.
Try using search term Template literals
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:
var a = 5; var b = 10; console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`); // "Fifteen is 15 and // not 20."
Upvotes: 1