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

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Utilizing numerous Nuxt vuetify textfield components as properties

Trying to create a dynamic form component that can utilize different v-models for requesting data. Component: <v-form> <v-container> <v-row> <v-col cols="12" md="4"> <v ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Directive's ng-click function fails to execute

This directive contains a function that should be executed when clicked. ebApp.directive('monthDir', function () { return { restrict: 'E', templateUrl: 'htmlFiles/monthDirective.html', transclu ...

Sharing Data Between Controllers in AngularJS

I am faced with a challenge involving two Angular controllers: function Ctrl1($scope) { $scope.prop1 = "First"; } function Ctrl2($scope) { $scope.prop2 = "Second"; $scope.both = Ctrl1.prop1 + $scope.prop2; //Ideally, I would like to achieve t ...

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

Retrieving PHP data, utilizing the split method to break apart the commas within the string, and then displaying the information within a div using AJAX for a continuous refresh cycle every 3 seconds

I am attempting to extract data from a PHP string like '10,58,72,15,4,723,' and split it by commas into arrays using the split() method. My goal is to then place these arrays into different div elements and update the data every 3 seconds. Below ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

Is there a way to activate and change the color of a Radio Button when it is clicked?

Is there a way to change the background-color of a clicked Radio Button so it appears highlighted? For example, when the first choice is clicked, I want it to stand out visually. This is the current UI displaying the choices: https://i.stack.imgur.com/a7 ...

VIDEOJS ERROR: A peculiar mistake has occurred. TypeError: The property 'value' cannot be read since it is undefined in the context of

Recently, I came across a fascinating plugin called videojs-thumbnails for video.js, and I'm eager to incorporate it into my angular component. However, I keep encountering an error that says: VIDEOJS: ERROR: TypeError: Cannot read property 'val ...

NodeJs ERROR: Module not found

When trying to launch an instance running ubuntu with express, I encountered a module not found error that does not occur on my Windows machine. Error Message: node:internal/modules/cjs/loader:1085 throw err; ^ Error: Cannot find module './src/c ...

"Encountering a 403 error while using the request method in Node.js

app.post("/",function(req,res){ // console.log(req.body.crypto); request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){ console.error('error:', error ...

Creating a personalized scrollball feature within a fancybox

Within my fancybox, I have a section with images that require a scroll bar. I currently have a scroll bar in place, but I am interested in implementing an anti-scroll (custom scrollbar) instead. I came across one option at https://github.com/Automattic/an ...

Utilizing AngularJS: Conditionally rendering ngIf within an array of objects containing unique properties

Facing a challenge with the ngIf directive that I have been struggling to resolve despite trying various solutions. In my scenario, I have an array of objects, each containing different properties. The structure is as follows: object = [ { ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

Incorporate a `fresh Audio` element into my redux repository

I'm attempting to include a new Audio element in my redux store. This is how my reducer appears: export const songsReducer = (state = {}, action) => { switch (action.type) { case "PLAY_SONG": return { ...state ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...