Locating the position of multiple repeated words

My question involves a complex laTeX string:

let result = "\\frac{x}{2}+\\frac{3}{x}"; 

The task at hand is to locate the instances of "frac" in the string, store their positions in an array, find the first '}' character after each occurrence of "frac", replace it with "}/", and finally eliminate "frac" from the original string.

I attempted to solve this issue using a code block, but encountered limitations when there were multiple occurrences of "frac".

let result = "\\frac{x}{2}+\\frac{3}{x}";

        if (result.indexOf("frac") != -1) {
            for (let i = 0; i < result.split("frac").length; i++) {

                let j = result.indexOf("frac");
                let permission = true;
                while (permission) {

                    if (result[j] == "}") {
                        result = result.replace(result[j], "}/")
                        permission = false;

                    }
                    j++;

                }
                result = result.replace('frac', '');
            }
        }
        console.log(result)

UPDATED OUTPUT: \\{x}//{2}+\\{3}{x}

If you have any suggestions on how I can enhance my code, I would greatly appreciate your input!

Answer №1

Is this something you were looking for?

frac(.+?)}

This code snippet defines a regex pattern to match the literal "frac" followed by a capture group that will capture one or more of any character .+ until it encounters a closing curly brace }, and then replace it with the captured content plus a forward slash.

The script utilizes the `replace` function to iterate over the matches and perform the replacement.

let equation = "\\frac{x}{2}+\\frac{3}{x}";
let positions = [];
const modifiedEquation = equation.replace(/frac(.+?)}/g,function(match, found, offset,string) {
  console.log(match,found,offset,string)
  positions.push(offset)
  return `${found}/`; // adding a slash to the found string
})
console.log(positions)
console.log(modifiedEquation)

Here is an alternative method using two sets of code:

let equation = "\\frac{x}{2}+\\frac{3}{x}";

let regex = /frac/gi, result, indices = [];
while ((result = regex.exec(equation))) {
   indices.push(result.index);
}
const newEquation = equation.replace(/frac(.+?)}/g,"$1}/")
console.log(indices)
console.log(newEquation)

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

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

Verify if the current day falls within the range of Monday to Sunday using Node.js

Currently developing a food delivery app similar to foodpanda. Encountering an issue where a restaurant's operating days are from Monday to Friday, and I need to prevent users from placing orders on Saturdays and Sundays (or any other specified servic ...

I am utilizing Vue.js to create a duplicate input field and dynamically increasing the index

When a user clicks on the "add another" button, I want to create a duplicate text input field and increase the index of the new field. I found this question that is similar, but the solution provided did not successfully increment the index. The current i ...

There was a problem with the ajax request

Attempting to make an ajax request in my SpringMVC project has been challenging. $.ajax({ contentType : 'application/json; charset=utf-8', type : 'get', url : 'order/get/'+i, dataType : 'json', ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

Encountering difficulty extracting information from JSON file within AngularJS factory

I am struggling with a Json file named discover.json located at json-files/discover.json {"data": [ {"username": "aky123", "name": "ajay"}, {"username": "sky123", "name": "sanjay"} ]} Below is my factory setup: var myAppServices=a ...

Troubleshooting issues with data parsing in an Angular typeahead module

Utilizing the AngularJS Bootstrap typeahead module, I am attempting to showcase data from an array of objects. Despite receiving data from my API call, I keep encountering the following error: TypeError: Cannot read property 'length' of undefine ...

Encountering an error with [object%20Object] when utilizing ajaxFileUpload

I wrote a JavaSscript script that looks like this: $.ajaxFileUpload({ url: url, secureuri: false, fileElementId: ['upload-file'], dataType: "JSON", data:{ "sample_path":$(".demo-view-container-left .vie ...

Tips for eliminating whitespace from an input field and then updating the field with the trimmed value

Currently, I am working on email validation where users might input empty spaces in the email field. To address this issue, I have implemented a logic to trim the input value using $trim and then re-assign it to the input field. Although everything seems ...

Currently, I am in the process of creating a game, but I am having trouble with my click event not functioning as expected on a dynamically

I'm currently working on a platform game and I've implemented a window.onload event that is supposed to trigger. Within this event, I am creating a div element, assigning it an ID, and then setting its onclick property. Despite being confident i ...

Transforming an array of JSON objects into a Knockout observable array containing observable properties

My application utilizes an ajax call to fetch a JSON array. [ {"ID":2,"Name":"Name 1","CreatedOn":"/Date(1432892160000)/"}, {"ID":7,"Name":"Name 2","CreatedOn":"/Date(1432892160000)/"}, {"ID":8,"Name":"Name 3","CreatedOn":"/Date(1432892160000)/"}, {"ID":9 ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...

Troubleshooting a minor JavaScript loop problem

I am facing an issue with my script that retrieves data from a database. Currently, when the search() function is called by clicking a button, only one result is displayed in a new div. How can I ensure that a new div is created for each result found, rath ...

The reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-con ...

Encountering a JavaScript Error: "e is null" while utilizing assert for checking JavaScript alert text

I encountered a javascript alert in my program that I was able to interact with by reading the text and clicking on the buttons. However, when I tried to verify the alert text using assertequals function, I faced an error. Here is the code snippet: String ...

The process of dynamically inserting input types into a <td> element using the innerHTML tag is not functioning properly in Internet Explorer

I am facing an issue with dynamically placing input types within a <td> tag - the innerHTML() method is not functioning properly in Internet Explorer, although it works fine in Mozilla. This is how I am inserting the input types using JavaScript, wi ...

Can the orientation of the card reveal be customized in Materializecss?

Exploring the card-reveal feature in the materializecss framework on this page: https://codepen.io/JP_juniordeveloperaki/pen/YXRyvZ with official documentation located at: In my project, I've rearranged the <div class="card-content"> to display ...

The instance is referring to "close" as a property or method during render, but it is not defined. Ensure that this property is reactive and properly defined

Upon my initial foray into Vue.js, I encountered a perplexing warning: vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "success" is not defined on the instance but referenced during render. Make sure that this property is reactive, e ...