Template Literal Backtick Syntax Quote Delimitation Tutorial

Template Literal Backtick Syntax Quote Delimitation Tutorial

Template Literal Backtick Syntax Quote Delimitation Tutorial

We spend quite a sizeable proportion of our programmatical coding time working out string variable creation where quotes, be they …

Here’s an example of a complex scenario from some Javascript code …


var lastcursor="Url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='66' height='48' viewport='0 0 100 100' style='border-radius:15px;background-color:rgba(0,0,255,0.3);fill:black;font-family:Verdana;font-size:17px;'><text y='80%'>Alt\\01f3d5</text></svg>\") 16 0, progress";

… which the Template Literal backtick syntax can simplify to …


var lastcursor=`Url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='66' height='48' viewport='0 0 100 100' style='border-radius:15px;background-color:rgba(0,0,255,0.3);fill:black;font-family:Verdana;font-size:17px;'><text y='80%'>Alt\\01f3d5</text></svg>") 16 0, progress`;

… with no backslashes needed to achieve the same result. This is a simple example, but please see a Javascript function reworked from that within the recent Form or Prompt Output Tagged Template Literal Tutorial blog posting thread.

Here’s the HTML and Javascript behind the iframe content below …


<html><head><script type=text/javascript>
var millis=7656757543;
var strings=[''], rest=';'

function myTag(strings, beingExp, ageExp, secondageExp, breedExp, streetExp, suburbExp, stateExp) {
let str0 = '';
let str1 = '';
let str2 = '';
let str3 = '';
let str4 = '';
let str5 = '';
let str6 = '';
let str7 = '';

for (var ii=0; ii<strings.length; ii++) {
if (ii > 7) {
rest+=' ' + strings[ii];
} else {
eval("str" + ii + ' = "' + strings[ii] + '"');
}
}

let ageStr;
if (ageExp > 99){
ageStr = 'centenarian';
} else {
ageStr = 'youngster';
}

// We can even return a string built using a template literal
return `${str0}${beingExp}${str1}${ageExp}${str2}${secondageExp}${str3}${breedExp}${str4}${streetExp}${str5}${suburbExp}${str6}${stateExp}${str7}` + rest;
}

if (document.URL.indexOf('?') != -1) {
alert(myTag(["one'str",2,3,4], "two'str", "III", "iv", 'seven"str', "six'str", "VII", "viii"));
alert(`seconds elapsed = ${Math.floor(millis / 1000)}`);
} else {
console.log(myTag(["one'str",2,3,4], "two'str", "III", "iv", 'seven"str', "six'str", "VII", "viii"));
console.log(`seconds elapsed = ${Math.floor(millis / 1000)}`);
}
</script></head><body><a style=text-decoration:underline; onclick='location.href=document.URL + String.fromCharCode(63);''=>Click to show backtick calculations to two alert popups</a></body></html>


Previous relevant Form or Prompt Output Tagged Template Literal Tutorial is shown below.

Form or Prompt Output Tagged Template Literal Tutorial

Form or Prompt Output Tagged Template Literal Tutorial

Yesterday’s Scrolling Logging Template Literals Primer Tutorial was the precursor to discussing “Tagged Template Literals” …

A more advanced form of template literals are tagged templates.

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. (Alternatively, it can return something completely different, as described in one of the following examples.)

… we’ve adapted into an HTML and Javascript tagged_template_literal.html codebase proof of concept web application closely using the start the webpages above started us with … thanks.

These “Tagged Template” logics helped us separate the chaff (small words magically handled via “Tagged Template” usage) from the wheat (form or prompt arguments formalized by our interactive input) in the English sentence … such as (today’s default) …

That Nala is a wonderful 9 year ( 81 in K9 years ) old Golden Retriever who lives at 33 Charles Street, Lawson, State of Wow.

… we produce as a result of all the efforts, here.


<html>
<head>
<title>Tagged Template Literals - RJM Programming - July, 2022 ... thanks to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals</title>
<style> input { width: 20%; } </style>
</head>
<body>
<h2 title='A Tagged Template Literal regimen is dealing with all the little word stuff between the arguments.'>Tagged Template Literals</h2>
<h3>RJM Programming - July, 2022</h3>
<h3>Thanks to <a target=_blank title='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals' href='//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals'>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals</a></h3>

<p id=blurb></p>

<script type='text/javascript'>
const prompt = location.search.split('prompt=')[1] ? (one,two) => { return window.prompt(one,two); } : (one,two) => { return two; };
const alert = location.search.split('prompt=')[1] ? (one) => { document.getElementById('blurb').innerHTML=one; return one; } : (one) => { return window.alert(one); };
let being = location.search.split('being=')[1] ? prompt('Being', decodeURIComponent(location.search.split('being=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('Being', 'Nala');
let age = location.search.split('age=')[1] ? prompt('Age',decodeURIComponent(location.search.split('age=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('Age','9');
let breed = location.search.split('breed=')[1] ? prompt('Breed',decodeURIComponent(location.search.split('breed=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('Breed','Golden Retriever');
let street = location.search.split('street=')[1] ? prompt('Street',decodeURIComponent(location.search.split('street=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('Street','33 Charles Street');
let suburb = location.search.split('suburb=')[1] ? prompt('Suburb',decodeURIComponent(location.search.split('suburb=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('Suburb','Lawson');
let state = location.search.split('state=')[1] ? prompt('State',decodeURIComponent(location.search.split('state=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('State','State of Wow');
let secondage = location.search.split('secondage=')[1] ? prompt('K9 Age', decodeURIComponent(location.search.split('secondage=')[1].split('&')[0]).replace(/\+/g,' ')) : prompt('K9 Age', '' + eval(eval('' + age) * 9));
let rest = location.search.split('rest=')[1] ? decodeURIComponent(location.search.split('rest=')[1].split('&')[0]) : '';

function doform() {
var ideas=['Being [' + being + ']', 'Age [' + age + ']', 'K9 Age [' + secondage + ']', 'Breed [' + breed + ']', 'Street [' + street + ']', 'Suburb [' + suburb + ']', 'State [' + state + ']'];
var aform='<form method=GET onsubmit="checkis();" action=./tagged_template_literal.html><br><br><input type=submit value=Show></input><br><br><input type=submit name=prompt id=prompt value=Prompt></input></form>';
for (var jj=eval(-1 + ideas.length); jj>=0; jj--) {
aform=aform.replace('>', '><input type=text onblur="if (this.value.length == 0) { this.value=this.placeholder.split(String.fromCharCode(91))[1].split(String.fromCharCode(93))[0]; }" id=' + ideas[jj].split('[')[0].toLowerCase().replace('k9 age', 'secondage') + ' name=' + ideas[jj].split('[')[0].toLowerCase().replace('k9 age', 'secondage') + ' placeholder="' + ideas[jj] + '" value=""></input><br>');
}
document.body.innerHTML+='<br><br>' + aform;
//alert(aform);
//document.getElementById(ideas[0].split('[')[0].toLowerCase().replace('k9 age', 'secondage')).focus();
window.setTimeout(function () {
document.getElementById('being').focus();
}, 1000);
}

function checkis() {
var eis=document.getElementsByTagName('input');
for (var jis=0; jis<eis.length; jis++) {
if (eis[jis].value == '' && ('' + eis[jis].placeholder).indexOf('[') != -1) {
eis[jis].value=eis[jis].placeholder.split(String.fromCharCode(91))[1].split(String.fromCharCode(93))[0];
}
}
}

function myTag(strings, beingExp, ageExp, secondageExp, breedExp, streetExp, suburbExp, stateExp) {
let str0 = '';
let str1 = '';
let str2 = '';
let str3 = '';
let str4 = '';
let str5 = '';
let str6 = '';
let str7 = '';


for (var ii=0; ii<strings.length; ii++) {
if (ii > 7) {
rest+=' ' + strings[ii];
} else {
eval("str" + ii + ' = "' + strings[ii] + '"');
}
}

let ageStr;
if (ageExp > 99){
ageStr = 'centenarian';
} else {
ageStr = 'youngster';
}

// We can even return a string built using a template literal
return `${str0}${beingExp}${str1}${ageExp}${str2}${secondageExp}${str3}${breedExp}${str4}${streetExp}${str5}${suburbExp}${str6}${stateExp}${str7}` + rest;

}

let output = myTag`That ${ being } is a wonderful ${ age } year ( ${ secondage } in K9 years ) old ${ breed } who lives at ${ street }, ${ suburb }, ${ state }.`;

if (document.URL.indexOf('being=') != -1) {
alert(output);
// That Mike is a youngster.
}

doform();
</script>

</body>
</html>


Previous relevant Scrolling Logging Template Literals Primer Tutorial is shown below.

Scrolling Logging Template Literals Primer Tutorial

Scrolling Logging Template Literals Primer Tutorial

Yesterday’s Screen Capture API Download Video Tutorial‘a web application code, thanks to Using Screen Capture, used interesting Javascript Template Literals

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.

Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation (to create strings by doing substitution of placeholders). However, a tagged template literal may not result in a string; it can be used with a custom tag function to perform whatever operations you want on the different parts of the template literal.

we’ve adapted for use today in our very simple “Scrolling Logging” console_override.html web application that scrolls like for a command line interactive terminal session …


<html>
<head>
<title>Console Message Override - RJM Programming - July, 2022</title>
<script type='text/javascript'>
var logElem=null;
var firstisnot=false;
var ii=0;

function onl() {
logElem=document.getElementById('log');


console.log = msg => logElem.innerHTML += (firstisnot ? '<span id=span' + ii + '></span>' + document.getElementById('topbit').innerHTML : '') + `${msg}<br>Brought to you via console.log at ` + new Date() + `<br><br>`;
console.error = msg => logElem.innerHTML += `<span class="error">${msg}<br>Brought to you via console.error at ` + new Date() + `</span><br><br>`;
console.warn = msg => logElem.innerHTML += `<span class="warn">${msg}<br>Brought to you via console.warn at ` + new Date() + `<span><br><br>`;
console.info = msg => logElem.innerHTML += `<span class="info">${msg}<br>Brought to you via console.info at ` + new Date() + `</span><br><br>`;


console.log('A console.log message.');
console.error('A console.error message.');
console.warn('A console.warn message.');
console.info('A console.info message.');


if (firstisnot) {
document.getElementById('span' + ii).scrollIntoView();
}
ii++;
firstisnot=true;


setTimeout(onl, 4045);
}

</script>
</head>
<body onload='onl();'>
<div id=topbit>
<h2>Console Message Override</h2>
<h3>RJM Programming - July, 2022</h3>
</div>
<h4 id=log></h4>
</body>
</html>

in action below

If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.

This entry was posted in eLearning, Tutorials and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *