Can the tag function arguments be employed to generate an identical sequence of literals and placeholders?

A section from the tutorial on template strings at this link includes an interesting example:

var say = "a bird in hand > two in the bush";
var html = htmlEscape `<div> I would just like to say : ${say}</div>`;

// A basic tag function
function htmlEscape(literals, ...placeholders) {
    let result = "";
    ...
   // Combine the literals with the placeholders
   for (let i = 0; i < placeholders.length; i++) {
     result += literals[i];
     result += placeholders[i]

Can we generate the exact same escaped input string if the order of placeholders is changed? What happens if the placeholder is placed before the literal text?

Explanation

The creator of the html escape function assumes that the first literal should be output first. But what if the placeholder ${say} is positioned first? In essence, do tag functions have the ability to determine the sequence of placeholders and literals used?

Answer №1

A template literal always initiates and concludes with a component character, which interchanges with substitutions. It consistently contains one additional string section compared to substitutions. A placeholder is incapable of being positioned at the very beginning - however, it may follow an empty string:

const speak = 42;
marker `{speak} that way`;
function marker(strings, ...positions) {
    console.assert(strings[0] === "")
    console.assert(strings[1] === " that way");
    console.assert(positions[0] === 42);
    console.assert(strings.length == positions.length+1);
}

It should be noted that a tag function is unable to generate placeholders (labels), as it lacks awareness of them. It simply receives the placement values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to adjust an object's property later on?

Working with KineticJs, I aim to efficiently handle elements by creating objects for easy management. Below is my code which is not functioning as expected. (I am relatively new to object-oriented programming and still learning) $(function(){ v ...

How to implement angular 2 ngIf with observables?

My service is simple - it fetches either a 200 or 401 status code from the api/authenticate URL. auth.service.ts @Injectable() export class AuthService { constructor(private http: Http) { } authenticateUser(): Observable<any> { ...

What location is optimal for storing ng-templates within an Angular/Django single-page application?

My project involves using Django and AngularJS to create a single-page application. I have numerous ng-templates structured like this: <script type="text/ng-template" id="item.html"> // content </script> Currently, all these templates are l ...

Tips for successfully accessing a variable in an Angular Pipe

When displaying output, I need to show a specific number of decimal digits based on the length returned by a stored procedure. The length of these decimal digits can vary, and I only need to focus on the decimal part, not the integer part. To achieve this, ...

Utilizing TypeScript decorators for Node.js authentication and authorization

In the process of developing a server-side Node.js application using TypeScript, I have come to the point where I need to implement authorization. My initial plan was to utilize TypeScript "Method and Class Decorators" for this purpose. However, I came acr ...

Best Practices for Storing Static JSON Data in a Chrome Extension

In my extension, I have a collection of around 350 lines of static JSON data. This data is essential for the functioning of a content script, as it consists of key-value pairs that are checked upon user interaction to trigger specific actions. Here's ...

Strategies for transferring a dynamic variable to a parent window's form in JavaScript?

What is the best way to use a changing parameter name when accessing a variable? For instance: opener.document.form.namerow_3.value = this.cells[0].innerHTML; opener.window.form.{varaible}.value=this.cells[0].innerHTML; In this scenario, the parameter ...

Troubleshoot issues within ExpressJS

I am encountering an issue with the debugger in Visual Studio Code. It crashes upon startup, but runs smoothly when using nodemon to start the server. My application is connected to a MySql Database. I have attempted to reinstall the module without succes ...

Implementing a blur effect on a CSS loader

I have successfully implemented a loader feature where a loading animation is displayed upon clicking the submit button, indicating that the form submission is in progress. However, I am encountering an issue when trying to apply a blur effect to the entir ...

What is the purpose of the `Bitwise operator |` in the `d3.shuffle` source code and how can it be understood

Learning about the Bitwise operator | can be found in the document here and a helpful video tutorial here. However, understanding the purpose and significance of | may not come easily through basic examples in those resources. In my exploration of the sou ...

Transferring the selected radio button from one HTML page to another without using PHP

I'm looking to transfer radio button data from the first HTML to the second using Pure JavaScript Feel free to use jQuery if needed. jQuery was used 1st HTML <body> <label for="1"> <input type="radio" name="num" id="1" checked="che ...

The javascript code appears to be functioning properly on desktop browsers but is not functioning as expected on Chrome's mobile browser

On my WordPress site, I have created a Java Bootstrap loan calculator that works perfectly on desktop. However, when I use Chrome on mobile, it is not functioning properly. I tried using the wp-coder plugin and also manually added the necessary code. Int ...

Is there a way to dynamically add an option to multiple select boxes and then only redirect the browser if that specific option is chosen using jquery/js?

Presently, this is the code I am working with. The URL validator is specifically included because there was an issue with redirection occurring on any option selected, however, I only want a redirect to happen when the options I add with jQuery are clicked ...

Node.js app not rendering ejs file despite using res.render() method, no error being thrown

I am encountering an issue where, when sending an ejs templated file as a response to a HTTP request, the HTML and CSS render properly but the Javascript does not respond. Even though the Javascript sources are linked in the head of the ejs response, the f ...

Align the timing of the animation with the dataset in ThreeJS

I am faced with the challenge of working with data that includes time in milliseconds and the x, y, z position of an object at each specific time interval. msec |pos_x |pos_y |pos_z ------------------------------ 0 |318 |24 |3 25 |3 ...

Using a loop to draw lines on a canvas

Gaining a preliminary understanding of java-script and canvas. I have managed to create steps and draw the initial two lines. I aim for this sequence to repeat 7 times. 7 p1's and 6 p2's in essence, it descends 7 times and moves across ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

Tips for including multiple JSON results into a single text box for auto-complete purposes

I am trying to combine different autocomplete list results into one text box. It's straightforward to use separate text boxes for different autocomplete results. HTML: <input id="university" name="university" type="text" /> <input id="unive ...

Alternative method for displaying text in Discord

At the moment, my discord bot is set up to read from a file and post the new data in that file to a specific channel. I am interested in modifying the output so that any characters enclosed in ~~ are displayed as strikethrough text. const Bot = require( ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...