Skip to content

Instantly share code, notes, and snippets.

@jerbear2008
Last active February 5, 2022 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerbear2008/26537b1da80cb0486aa39128aab75318 to your computer and use it in GitHub Desktop.
Save jerbear2008/26537b1da80cb0486aa39128aab75318 to your computer and use it in GitHub Desktop.
Tagged Template Literals
(a=>{console.log(a[0])})
`test`
((strings) => { // tag for template literal
console.log(strings[0]) // log first string
})`test` // immediatley use as a tagged template literal
let a = 1
let b = '1'
console.log(`the value of a is ${a} and the value of b === a is ${b === a}.`)
function tagOne(strings, ...expressions) {
strings = Array.from(strings)
let output = strings[0]
for (let i in expressions) {
i = Number(i)
let expression = expressions[i]
output += `${typeof expression} ${expression}`
output += strings[i + 1]
}
return output
}
console.log(tagOne`string example: ${'test' + 'ing'}, number example: ${1 + 2}, the end.`)
// string example: string testing, number example: number 3, the end.
function tag(strings, ...expressions) {
// strings is an array-like object with all the string fragments
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates:~:text=Tags%20allow,expressions.
// expressions is an array of all the expressions within ${}
}
tag`string1${'expression1'}string2${'expression2'}string3`
tag `text`
tag
`text`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment