Not all matches are undergoing regex replacement as intended

Is there a reason why the code snippet provided is not correctly performing regex operations on all instances of {{ ... }} placeholders? The input string below is a condensed version of the original content.

Check out this link for the code snippet

var input = "{{ %1$@ }} / {{ %1$@ }} ({{ %2$@ }}) {{ %1$@ }} {{ %1$@ }} {{ %1$d }} {{ %1$@ }} of {{ %2$d }} of {{ %3$d }}";

var regex = /(\{\{ \%(\d)\$(.) \}\})/g;

var match;
while (match = regex.exec(input)) {
    console.log(match);
    input = input.replace(match[0], '%@' + match[2]);
}

console.log(input);

Answer №1

When you modify the input variable before exec completes, it causes the issue of moving forward in index while the string is shrinking.

To address this problem, consider adding another variable, wrapping the code in a separate function, or using the replace method as suggested by @dfsq:

var input = "{{ %1$@ }} / {{ %1$@ }} ({{ %2$@ }}) {{ %1$@ }} {{ %1$@ }} {{ %1$d }} {{ %1$@ }} of {{ %2$d }} of {{ %3$d }}";

var regex = /(\{\{ \%(\d)\$(.) \}\})/g;
var output = input;
var match;

while (match = regex.exec(input)) {
    console.log(match);
    output = output.replace(match[1], '%@' + match[2]);
}

alert(output);

Answer №2

When utilizing the exec method to search for multiple occurrences, it initiates each iteration from the index of the last match found:

If your regular expression includes the "g" flag, you can employ exec() repeatedly to locate successive matches within the same string. In such cases, the search commences at the substring of str specified by the lastIndex property of the regular expression (the test() function will also modify the lastIndex property).

In this scenario, a more straightforward and neater approach would be to utilize the String.prototype.replace method:

var input = "{{ %1$@ }} / {{ %1$@ }} ({{ %2$@ }}) {{ %1$@ }} {{ %1$@ }} {{ %1$d }} {{ %1$@ }} of {{ %2$d }} of {{ %3$d }}";

var regex = /(\{\{ %(\d)\$(.) \}\})/g;

input = input.replace(regex, '%@$2');

alert(input);

Answer №3

To enhance the regular expression, my recommendation is to eliminate unnecessary groups within it,

/\{\{ %(\d)\$. \}\}/g can be used instead of /(\{\{ %(\d)\$(.) \}\})/g. For a more concise and coherent approach, you could opt for the following replacement method:

let input = "{{ %1$@ }} / {{ %1$@ }} ({{ %2$@ }}) {{ %1$@ }} {{ %1$@ }} {{ %1$d }} {{ %1$@ }} of {{ %2$d }} of {{ %3$d }}";
let output = input.replace(/\{\{ %(\d)\$. \}\}/g, "%@$1");

The resulting value of the output variable will be

%@1 / %@1 (%@2) %@1 %@1 %@1 %@1 of %@2 of %@3

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

Troubleshooting: Stage element not being recognized by Angular and CreateJS

I'm currently working on an Angular view that inherits from an ng-view element. Within the view file, there is a canvas that is controlled by a specific controller. My goal is to bring up a stage that allows me to add elements onto the canvas. Howev ...

The new URL identifier is malfunctioning, as well as the local storage cache in Internet Explorer

I'm experiencing an issue with the new URL method ('id') in Internet Explorer. Below is the code snippet that I am using: $("#content .left").hide(); $('#'+activeTab).show(); $('#side-menu-parent li a').click(f ...

Trouble with sending arguments to Express middleware

I'm currently working on developing a custom input validation middleware using Express. My aim is to create a middleware that takes 2 parameters in order to validate client input effectively. Despite referencing various sources, including the Express ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

What is the best way to incorporate tinymce into webpack?

I am facing an issue with integrating tinymce with webpack. It assigns a property called tinymce to window, so one solution is to use the following syntax to require() it (as explained in the bottom of the EXPORTING section of the webpack documentation): ...

What could be causing my unique Angular custom date filter to output nonsensical results?

This is the Jade markup: .col-md-9 | {{client.person.date_of_birth | date:'standardDate'}} Here's the filter in Angular: .filter('standardDate', function($filter){ var dateFilter = $filter('date'); ...

Searching for table row elements using CSS and Vue.js

I am trying to alternate row colors in a table, but for some reason all rows end up being gray. <table> <tr v-for="i in item.env_vars" :style="{'background': index % 2 === 0 ? '#eee' : '#ccc' }"> & ...

Activate the bootstrap modal display using PHP code

Can someone help me trigger the modal('show') event using PHP code? I attempted the following: if(isset($_POST['Edit'])){ echo "<script> $('#Modal').modal('show') </script>"; } I tested this code, but i ...

Choose a single checkbox to select all options within a bs-table row

After successfully using bs-tables to pass selected rows through checkboxes, I am now faced with the challenge of sending data from all rows when just one checkbox is selected. The code below depicts my current approach for passing data of single and mul ...

Encountering an Error when attempting to read and update with Knex.js

I am attempting to sequentially perform read and update operations. Initially, I retrieve data from the database using the id, then I modify it and aim to update the data in the database as well. However, I encounter an error stating "Unhandled rejection E ...

The postman does not retain any data

I am currently facing an issue where I am using Postman to enter a post into a MongoDB server, but the post returns empty. Even after checking my server, nothing has been entered and there are no errors displayed. Here is the route file: router.post(&apos ...

JavaScript: The element containing only text

I'm having an issue with the code snippet from the W3Schools website. When I use the LI element in a straight line, it works fine. But when I try to format it differently, it doesn't work. Any ideas on what could be causing this? This is the cod ...

In Cypress, I am trying to specifically choose only numerical values from a dropdown menu. However, the list contains a mix of alphanumeric and numeric values

Looking to streamline: This is my code: cy.get('[role=presentation]') cy.get('[role=row]').find('td') .get('[role=gridcell]').eq(9).click().wait(2000) cy.get('[role=listbox]').get('[role=option]& ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

clicking on internal links in the bootstrap side menu causes it to jump

Im trying to add a side menu to a help page. The menu and internal links are functioning properly, but when clicked, the side menu partially goes behind the navbar. As a beginner, I'm not sure how to resolve this issue. Can someone offer some guidan ...

Web Browser cross-origin AJAX requests

Recently, I developed an Internet Explorer extension that injects a script every time a page is accessed. The purpose of this script is to send an AJAX request to my localhost. However, I have encountered a roadblock where the request only works if it&apos ...

The Bootstrap navigation bar is experiencing functionality issues when viewed on Chrome mobile browsers

I'm currently testing out the bootstrap 3 navbar feature on my meteor application, but I'm encountering some issues specifically on mobile devices. The problem seems to be that the toggle button is not showing up as expected. Interestingly, it wo ...

Utilizing Vue3's Ref feature within a component?

Currently, I am developing an input component for my login form to avoid creating the input tag repeatedly whenever it is needed. In my previous implementations without components, I was able to save the input value at the @input event using refs (by acces ...

Using regular expressions to filter certain Persian words in PHP

Currently, I am developing a script that can detect offensive words in text messages. One challenge I face is when users intentionally modify words to make them harder to identify. My goal is to ensure my code can still recognize these altered words as eff ...