Substitute the expression with placeholders for JavaScript variables

Looking for a JavaScript regex pattern that will replace all instances of {{variableName}} with the corresponding JavaScript variable placeholders in a given string, such as ${variableName}.

let str = 'Lorem ipsum dolor {{variable1}}, sit amet consectetur {{otherVaraible}} elit. Iure facilis quaerat obcaecati tempore {{variable2}} praesentium, nisi culpa vero';

Desired Output:

let str = 'Lorem ipsum dolor ${variable1}, sit amet consectetur ${otherVaraible} elit. Iure facilis quaerat obcaecati tempore ${variable2} praesentium, nisi culpa vero';

Thank you!

Answer №1

One method involves using regex for replacing text. Here is an example in code:

 run1.onclick = function() {
  output1.innerHTML = input1.value.replace( /{{(.*?)}}/g, '${$1}'); 
}
<input id="input1" type="text" value="'Lorem ipsum dolor {{variable1}}, sit amet consectetur {{otherVaraible}} elit. Iure facilis quaerat obcaecati tempore {{variable2}} praesentium, nisi culpa vero'">
<input id="run1" type="button" value="run">
<br />
<span id="output1"></span>

Answer №2

Here is a sample created using regex101.com.
Feel free to experiment with it here

const regex = /{{(.*?)}}/gm;
const str = `Lorem ipsum dolor {{variable1}}, sit amet consectetur {{otherVaraible}} elit. Iure facilis quaerat obcaecati tempore {{variable2}} praesentium, nisi culpa vero`;
const subst = `${$1}`;

// The substituted value will be stored in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

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

Error in jQuery when trying to access the src attribute of an image: "undefined src

Just started delving into jQuery. I'm trying to grab the image source and showcase it in a fixed division like a pop-up, along with the image title. However, I'm encountering difficulties in fetching the image source. My attempt with the .attr() ...

Ways to verify if the scroll bar of a user is not visible

Is there a method to detect if the user has forcibly hidden the scroll bar in the operating system? 1. Automatically based on mouse or trackpad 2. Always 3. When scrolling I want to adjust the width of an HTML element if the scroll bar is visible, which c ...

Competition among fetch requests

I am currently developing a tracker that is designed to gather data from our clients' websites and send it to our API using fetch requests when site users navigate away from the page. Initially, I planned to utilize the beforeunload event handler to ...

TypeScript: The RegExp element is inferred to have an 'any' type by default

Looking to develop a function that can handle duration strings like 12ms, 7.5 MIN, or 400H, and then convert them into milliseconds. const units = { MS: 1, S: 1 * 1000, MIN: 60 * 1 * 1000, H: 60 * 60 * 1 * 1000 } export function toMS(str: strin ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array. // Here is the array of user ids const followedIds = follow.map((f) => f.followed); console.log(followedIds); // This will log [ '5ebaf673991fc60204 ...

"Change the value of a style setting in React to 'unset

One of the components has CSS properties such as `right` and `bottom` that are set with a classname. I tried to override these values using the `style` prop but have only been successful in setting numerical values like `10px` or `0px`, not `unset`. Wha ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Incorporating React-Native components into a Next.js application within an Nx monorepository: A Step-by-Step

I'm encountering an issue while attempting to integrate React Native components into an Nx monorepo setup. Initially, the Nextjs app compiles successfully: info - Fast Refresh enabled for 1 custom loader event - client and server compiled successful ...

What is causing express.js not to authenticate properly?

I'm currently in the process of developing a server application using node.js, which is up and running on localhost:8080. As I attempt to make a login request, I've encountered an issue where one method works while the other fails. My suspicion i ...

jquery accordion not functioning properly following partial ajax page refresh

Initially, I'm using a jQuery accordion that works perfectly. However, I encounter an issue when implementing some Ajax commands to reload part of the page, specifically the inner body section. After the page reloads, the accordion breaks because the ...

Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any as ...

Showing a Remote Image on the Screen

I have a 16x16 grid of thumbnail images and I'm trying to implement a feature where clicking on an image displays the full-sized version with a dimmed background. The full-sized image should appear to float above the background. I don't want to ...

What steps can I take to ensure that the full tingle modal, which includes an image, is visible when the

Upon loading the page, I noticed that if the browser width is greater than 540px, the modal displaying an image gets cut off (see figure below). What steps should I take to ensure that the vertical scroll bar appears immediately? https://i.sstatic.net/cJv ...

Interacting with objects in a loaded OBJ model using ThreeJS

I have an obj model representing a map with tree objects. After successfully loading the model, I am trying to access one specific tree object named Tree1. How can I achieve this? Currently, my code looks like this: loader.load( 'map.obj', fun ...

The functionality of the browser's back button is impaired when the window.location.href is modified

My application used to be written in jQuery and was not SPA. I have recently converted some of the pages to AngularJS, making them SPA. Now, I am faced with the challenge of ensuring proper communication between these two types of apps. When transitioning ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

Warning: Unhandled promise rejection - Type error encountered when trying to access property

While working on a simple login validation, I encountered an issue when deliberately inputting an incorrect email in the login post method via postman. UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of null at C:&b ...

Retrieve the IDs of all currently logged in users using express.js

Currently, I am working on a project and need to extract a list of user ids of all currently logged in users. I came across a relevant question on StackOverflow at this link. However, I am facing difficulties in accessing the object properties as intended. ...

Using Google Apps Script to input data into the next available row

Utilizing Google Apps Script, I am retrieving data from another spreadsheet and storing it daily in a sheet named "DATABASE". Although my current solution is basic, it keeps overwriting existing data. I wish to enhance the script to copy data from the imp ...