Searching for mustache variables in HTML using regular expressions is a helpful way to

As I work on parsing template files in my code, one of my first tasks involves removing all Mustache variables in the template. The majority of these variables follow this structure:

{{variable}}, {{#loop}}{{content}}{{/loop}}, {{^not}}{{/not}}, {{! comment }}, {{#if}}{{/if}}

Up until now, I've been using the following regex replace method to successfully eliminate these variables:

markup.replace(/\{\{[^\}\}]*\}\}/g, "")

However, I recently encountered an issue where I discovered a Mustache comment that encloses some javascript code.

{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}
  • Please note: The .js code within the comment does NOT include }}.

Initially, I believed that my regex would search for {{ until it reached }} (exactly 2 in a row) ([^\}\}]), but this is not the case. The matching process halts as soon as it encounters a single }, resulting in the failure to remove this comment from the template file since it couldn't identify the opening and closing {{ }} pair.

Query: How can I modify my regex to ensure it captures from '{{' to '}}' without pausing at a single '}'?


Sample scenarios:

"<p>{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p>{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}</p>" 
// incorrect - should be "<p></p>"

"<p>{{test}}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p></p>" // correct

"<p>{{#test}}{{.}}{{/test}}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p></p>" // correct

"<p>{{>partial}}</p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p></p>" // correct

"<p {{#flag}}class='fancy'{{/flag}}></p>".replace(/\{\{[^\}\}]*\}\}/g, "");
"<p class='fancy'></p>" // correct

Answer №1

Here is the solution:

> "{{! App.doStuff('magic_string')({flag:true, flag2: true}); }}".replace(/\{\{(?:(?!}}).)*\}\}/g, "")
'<p></p>'

DEMO

Explanation:

\{                       '{'
\{                       '{'
(?:                      group, but do not capture (0 or more
                         times):
  (?!                      look ahead to see if there is not:
    }}                       '}}'
  )                        end of look-ahead
  .                        any character except \n
)*                       end of grouping
\}                       '}'
\}                       '}'

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

When you drag and drop multiple items, the entire data set is erased

I am currently working on a grid that loads data from a JSON file in a React application. When a user holds down the ctrl key on an item, that item is tagged with a new property called selected. My goal is to enable the user to drag and drop the tagged ite ...

Utilizing Meta Tags to Enable JavaScript Execution within a Chrome Extension

Introducing my latest creation: Frogga, a Chrome Extension that can be accessed from Frogga on GitHub I've been experimenting with different approaches, but I'm only able to access the initial JSON layer. I have the potential to dig deeper, but ...

Configuring IP Whitelisting for Firebase Cloud Functions with MongoDB Cluster

What is the process for including my Firebase Cloud Functions in the IP whitelist of my MongoDB cluster? Error Message: ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

tagit: update the label's value

I've been utilizing the jquery ui plugin https://github.com/aehlke/tag-it to incorporate tagging functionality into my project. This is how I am creating tags: $("#Input").tagit("createTag", "ABC"); My goal is to append additional text to the labe ...

Migrating to Angular Universal for server-side rendering with an external API server

Thank you for taking the time to read my query. I have developed a project using server-side Node.js and client-side Angular 6. The purpose of the app is to provide information on cryptocurrency prices and details. I am now looking to transition my Angu ...

Troubleshooting problem with GZIP in Angular 2 application deployment

I have developed an Angular 2 TypeScript application. I am using Firebase for hosting and Cloudflare for optimizing speed, caching, and security. When checking the browser header, it indicates: accept-encoding:gzip, deflate, sdch, br The app.js file has ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

Vue event emissions are not triggered or detected

This is the functionality of the Child Component: registerUser() { if (this.$refs.form.validate()) { this.$emit('showLoader', true); // Triggers this.$fireAuth .createUserWithEmailAndPassword(this.email, this.password) .the ...

"Clicking the button will clear the values in the input fields

I have encountered a strange issue that I've never seen before. When I try to input the value of scope upon clicking on <a>, everything works fine. However, if I have entered values in other inputs and then click on <a> again, the values i ...

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

Implement the color codes specified in the AngularJS file into the SASS file

Once the user logs in, I retrieve a color code that is stored in localstorage and use it throughout the application. However, the challenge lies in replacing this color code in the SASS file. $Primary-color:#491e6a; $Secondary-color:#e5673a; $button-color ...

Only the initial TinyMCE editor that was added dynamically is visible, the rest are not showing

I am currently developing a javascript application that will showcase a real-time discussion thread. The app will regularly communicate with the server to fetch new data and display it on the page. To enable users to post comments and replies, we have deci ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

A versatile JavaScript function built to efficiently validate numerous forms across a webpage

Sorry for the simple query, but I'm still learning JavaScript. I have a script that checks if a text field is empty to validate user inputs. If it's not empty, a confirmation window pops up before submitting the form and uploading the information ...

AngularJS - Controller routing to open link in new tab based on condition

Within my application, there are two distinct types of profiles available for organisations. When a user interacts with a profile name, the system must first determine if a premium profile exists for that organisation. If a premium profile is found, the us ...

Exploring the contents of this JSON array

I'm trying to fetch data from this link: <script type="text/javascript"> $.getJSON('http://api01.notaion.com/?item&id=120001462', function(data) { }); </script> I am uncertain whether I need to use a callback=?, a ...