What is the best way to convert template interpolation using different words into a correct expression syntax in JavaScript regex?

I have a string that contains template interpolation along with words that are not inside the interpolation. The string can be in one of these various forms:

foo{{bar}}
{{foo}}bar
foo{{bar}}baz
{{foo}}{{bar}}
foo
{{foo}}
{{foo}}bar{{baz}}

The text interpolation can appear multiple times in the string and there can be more than one word not inside the interpolation.

I need to transform the string as follows: remove the double curly brackets and keep the content, while the words outside the brackets should be wrapped in single quotes and concatenated using +.

The final result should generate a new string like this:

foo{{bar}}       // <-- 'foo' + bar
{{foo}}bar       // <-- foo + 'bar'
foo{{bar}}baz    // <-- 'foo' + bar + 'baz'
{{foo}}{{bar}}   // <-- foo + bar
foo              // <-- 'foo'
{{foo}}          // <-- foo
{{foo}}bar{{baz}} //<-- foo + 'bar' + 'baz'

For this, I created a regex expression

str.replace(/{{(.*?)}}/g, '$1').replace(/\b(\w+)\b/g, "'$1'")

The first regex removes the double curly brackets. The second regex wraps words in single quotes.

However, every result is getting wrapped in single quotes and there is no concatenation between them (not sure where to use + in which regex).

How can I modify the regex to meet my requirements?

const strs = [
  'foo{{bar}}',
  '{{foo}}bar',
  'foo{{bar}}baz',
  '{{foo}}{{bar}}',
  'foo',
  '{{foo}}',
  '{{foo}}bar{{baz}}'
];

let result = strs.map((s) =>
  s.replace(/{{(.*?)}}/g, '$1').replace(/\b(\w+)\b/g, "'$1'")
);

result.forEach((r) => console.log(r));

Check it out on StackBlitz

Answer №1

Instead of substituting, consider matching bracketed segments or non-bracketed segments. Then you can associate each bracketed segment with a substring without brackets and each non-bracketed segment with its version containing single quotes. Finally, concatenate with +s.

const items = [
  'foo{{bar}}',
  '{{foo}}bar',
  'foo{{bar}}baz',
  '{{foo}}{{bar}}',
  'foo',
  '{{foo}}',
  '{{foo}}bar{{baz}}',
];

let output = items.map((item) =>
  item
    .match(/{{[^}]+}}|[^{]+/g)
    .map(substring =>
      substring.startsWith('{')
        ? substring.slice(2, substring.length - 2)
        : "'" + substring + "'"
    )
    .join(' + ')
);

output.forEach((out) => console.log(out));

{{[^}]+}}|[^{]+ - match either

  • {{[^}]+}} - Non-} characters inside {{ }}, or
  • [^{]+ - One or more non-{characters

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

creating a Vuejs button function that will add together two given numbers

Help needed with VueJs code to display the sum of two numbers. Seeking assistance in developing a feature that calculates the sum only when the user clicks a button. Any guidance would be greatly appreciated! <!DOCTYPE html> <html lang="en"> ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

Getting to a nested key in a JSON object with JavaScript: a step-by-step guide

Currently, I'm working with a JSON file and need to extract the fileName tag for use. { "dataset": { "private": false, "stdyDscr": { "citation": { "titlStmt": { "titl": "Smoke test", "IDNo": ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

I am unable to populate MongoDB references using Node.js

I need to display the user's location details on the screen. For example: name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy" When the getuser function is called, I want to show the City and Town name. This is the implementation: U ...

Enhancing the appearance of individual cells within an HTML table by applying custom classes

I'm in the process of automating report generation for my organization. Our workflow involves using R to summarize data from Excel, then utilizing Rmarkdown, knitr, and the "htmlTable" package to generate HTML files. Currently, I am implementing CSS ...

Implementing Jquery tabs into the code causes the vertical auto-scroll to smoothly glide beyond anchor points

I recently implemented a smooth autoscroll feature on my webpage using the CSS-Tricks code found here: http://css-tricks.com/snippets/jquery/smooth-scrolling/ Everything was working perfectly until I added jQuery tabs to display some of the content. Now, ...

The EJS template on the Express app is encountering an issue: it is unable to find the view "/id" within the views directory located at "/home/USER/Desktop/scholarship-app/views"

When attempting to render the request URL for an ID in my Express app, I encountered the following error: Error: Failed to find view "/id" in views directory "/home/USER/Desktop/scholarship-app/views" Here is a portion of my Express app code: app.get(&a ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

JavaScript function fails to execute when attempting to call it after opening email client with attachment

//deliver the email to the recipient in eml format Response.ClearHeaders(); Response.Clear(); Response.Buffer = true; Response.ContentType = "message/rfc822"; Response.AddHeader("content-length", bin.Length.ToString()); Response.AddHead ...

Maxlength and Minlength attributes are not considered when using input type=“number”

Why is the maxlength attribute not functioning properly for this input element? <input type="number" maxlength="5" maxlength="10" /> ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

The algorithm for editing multiple phone numbers

I'm working on a form for my project that requires saving 4 phone numbers. The text boxes for entering the phone numbers are revealed on button clicks. Here's what I need to implement: When adding entries---> Enter the first phone number. C ...

JavaScript code in AJAX response functions properly in browsers like Firefox, Chrome, and Opera. However, it encounters issues in Internet Explorer 11, displaying an error message stating

After searching through various posts, I was unable to find a solution to my question. My query involves requesting a jQuery Datepicker via AJAX. I have provided an example for you to review in Firefox, Chrome or Opera: Ajax javascript example Unfortuna ...

having trouble with changing the button's background color via toggle

I've been experimenting with toggling the background color of a button, similar to how changing the margin works. For some reason, the margin toggles correctly but the button's color doesn't. <script> let myBtn = document.querySele ...

What is the best method for encrypting a URL that contains AngularJS data?

Here is the URL that needs to be encrypted: <a class="btn btn-success btn-sm btn-block" href="@Url.Action("myAction", "myController")?Id={{repeat.Id}}&HistoryId={{repeat.HistoryId}}" ng-cloak>View History</a> I am seeking guidance on enc ...

ASP.NET page experiences issues with executing Javascript or jQuery code

Having trouble with client scripts not functioning correctly on a child page that utilizes a master page. Looking for help to resolve this issue. <%@ Page Title="" Language="C#" MasterPageFile="~/Store.Master" AutoEventWireup="true" CodeBehind="NewSt ...

Show a persistent header once you scroll past a certain point using Bootstrap

Utilizing Bootstrap affix property to reveal a header after scrolling down by 100px has been successful for me. However, I encountered an issue when trying to set the opacity property to 0.0001, it works as expected. But when setting it to 0 or changing di ...

What seems to be the issue with this basic Node.js function not functioning properly?

I'm attempting to utilize a function that returns a boolean answer and then verifying it using if-else statements. function checkDNS(domain, tld) { var dns = require('dns'); dns.lookup(domain+'.'+tld, function (err, addres ...