Is it possible to retrieve the var name from an interpolated expression using template literals?

Suppose I have a variable like this:

myVar = `Some text with ${eggs} and ${noodles} or ${pies}`;

Is there a method to obtain myVar as an unprocessed string prior to variable substitution, essentially "Some text with ${eggs} and ${noodles} or ${pies}"?

My goal is to dynamically create an array containing the variable names (eggs, noodles, pies). Since I have multiple myVars, I want to avoid manually typing out each array.

Answer №1

When working with template literals, it is not possible to extract the variables from the literal string once they are inserted.

Instead of relying on a fixed set of variables, I recommend using a more dynamic approach by utilizing an array or another structured data organization.

var getText = (...a) => `Creating text with ${a[0]} and ${a[1]} or ${a[2]}`;

console.log(getText('apples', 'oranges', 'bananas'));
console.log(getText('cats', 'dogs', 'birds'));

Answer №2

When faced with a similar scenario, I decided to utilize strings instead of directly using string literals. I opted to extract variables using regex in the following manner:

const str = "my name is ${name} and I like to play ${sport}";
const variables = str.match(/\${\w*}/g);
console.log(variables)

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

Calculating the sha1 hash of large files using JavaScript in the browser without causing excessive memory usage

Is there a method to calculate the hash of large files in JavaScript without needing to load the entire file in a FileReader? Specifically, I'm interested in finding out if it's possible to stream a file and calculate its sha1 hash in JavaScript. ...

React is re-rendering the identical div elements once more - Delving into the concept of

After reading about reconciliation in the React documentation, an interesting scenario crossed my mind. In my examples, I have code that involves using a button element to toggle a boolean value on click event. Based on this value, the code utilizes a ter ...

A step-by-step guide on how to repeatedly reload a nextJS page using recursion and display an error page once the

I've been experimenting with a recursive page reload function that looks like this: export const refreshPage = (count)=>{ if (count <= 0){ // window.location.reload(); console.log("blue"); return }else { console.log(& ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

JavaScript's functionality akin to PHP's exec() function

I am searching for a way to run a shell command through javascript, similar to the functionality of PHP's "exec()" function. I understand that executing shell commands in javascript may not be recommended due to security concerns. However, my javascri ...

Utilize data binding in Typescript to easily link variables between a service and controller for seamless utilization

Is there a way to overcome the issue of value assignment not binding data in this scenario? For example, using this.arrayVal = someService.arrayVal does not work as intended. The objective is to simplify the assignment in both HTML and controller by using ...

Puppet Master: Retrieve the inner content

Is there a way to retrieve the innerHTML or text of an element? Or even better, how can I click on an element with a specific innerHTML? The approach in regular JavaScript would be as follows: let found = false; $(selector).each(function() { if (found ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

When you tap on the screen, the keyboard disappears and you have to hold

I have encountered an issue in my web view where I am programmatically creating an input field element using JavaScript and setting focus to it after creation. The problem is that the keyboard pops up for a split second and then closes when trying to focus ...

What is the best way to repeatedly execute a function upon button click?

for (let index = 0; index < shoppingCenters.length; index++) { const mall = shoppingCenters[index]; locateAddress(mall); } $scope.locateAddress = function(mall) {} XHTML <ion-nav-buttons side="primary"> <button class="button" ng-click= ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Step-by-step guide on setting up a click counter that securely stores data in a text file, even after the

Can anyone help me make this link actually function as intended? Right now it only runs the JavaScript code, but I would like it to run the code and redirect to a webpage. Additionally, I need the data to be saved to a text file. Please provide assistanc ...

Is there a way to activate the jquery event handler only when certain events occur in a particular sequence?

Currently, I am facing a particular scenario involving the use of Bootstrap tabs in combination with MarionetteJS. I want to ensure that when a tab is clicked, my designated handler function is only called after the 'show.bs.tab' event for that s ...

Displaying multiple categories of articles on a single page with Node.js

Seeking a solution to limit the number of posts displayed for each category using a .limit() function, but uncertain on how to proceed. Currently utilizing Mongoose and Express in my code setup. The existing code snippet is outlined below: router.get(&a ...

using hover/click functionality with a group of DIV elements

I have a group of DIV elements that I want to apply an effect to when hovering over them with the mouse. Additionally, when one of the DIVs is clicked, it should maintain the hover effect until another DIV is clicked. <div class="items" id="item1"> ...