I am attempting to use the .replace() method to swap out a specific string. Surprisingly, the first and last occurrences are successfully replaced, but

I am currently working on updating a specific string using the .replace() method. Interestingly, while the first and last occurrences are successfully replaced, the second one remains unchanged.

var text = "![alt text](https://www.reduceimages.com/img/image-after3.jpg) adadw  hjagwdjh ![alt text](https://www.reduceimages.com/img/image-after2.jpg)  akjhwdhawk ![alt text](https://www.reduceimages.com/img/image-afte1r.jpg)";

console.log("Final Result --- > " + formatText(text));

function formatText(content) {
const regex = /!\[(.*?)\]\((.*?)\)/g;

let m;
var printResult = (array) => {
content = content.replace(array[0], "<img src='" + 123 + "'>");
return false;
};

while ((m = regex.exec(content))) {

if (m.index === regex.lastIndex) {
regex.lastIndex++;
}

printResult(m);
console.log("After Replace " + content + "\n");
}

return content;
}

Answer №1

The query is how to transform the provided text into img tags with the URLs as src. This requires capturing certain groups:

I have updated the regex pattern to capture the URL:

!\[[^\]]*\]      # match the ![alt text]. Exclude from capture.
\(
 (               # start of group 1
 [^)]*           # capture the link
 )               # end of group 1
\)

We aim to replace the entire match with an img src=<group 1>. Here is the revised snippet:

var text = "![alt text](https://www.reduceimages.com/img/image-after3.jpg) adadw  hjagwdjh ![alt text](https://www.reduceimages.com/img/image-after2.jpg)  akjhwdhawk ![alt text](https://www.reduceimages.com/img/image-afte1r.jpg)";

console.log("FInal Result --- > " + formatText(text));

function toImg(str, group1) {
   return "<img src=\'" + group1 + "'>";
}

function formatText(content) {
  const regex = /!\[[^\]]*\]\(([^)]*)\)/g;
  return content.replace(regex, toImg);
}

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

Receiving an HTML form with a hidden input on the server: Best practices and steps to follow

On my webpage, there is an HTML form where a third party application adds a hidden input. How do I access this hidden input on the server side? If I'm unable to determine the exact name of the hidden input, can I retrieve the entire form on the serve ...

Guide to activating text entry following selection of a related radio button in Bootstrap 4

I am currently utilizing Bootstrap 4 to create a mock item submission form for my web application. Within the transaction row, the text input field for price is initially disabled by default. What steps should I take in order to enable the text input field ...

Need help with calling a PHP file through AJAX and verifying the accuracy of my PHP code?

Having never worked with PHP before, I am uncertain if my code is correct. I am attempting to execute my PHP file from my JavaScript/jQuery code using ajax, but it doesn't seem to be functioning properly. No emails are getting sent, and there are no e ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

I require limitless onclick functionality, but unfortunately, transitions are not functioning as expected

I'm currently working on creating a dynamic photo gallery, but I've encountered a couple of issues that need to be addressed... The "onclick" function in my JavaScript only allows for a single click, whereas I need it to be able to handle mul ...

When the client initiates, Meteor gets a head start

Can you explain why, on the client side, the variable init in if(init) is evaluated to be true even before init = true is called and when no new documents are added to the Orders collection? As a result, the query.observe function returns all documents ret ...

Adding complex JSON format to an HTML table involves formatting the data correctly and then using

Utilizing AJAX, I fetched a JSON response and am now looking to map the JSON data into an HTML table structured like this: { "records": [{ "type_id": 000001, "type_desc": "AAAAAA", "type_createby": "Adam" }, { "type ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Disabling the Bootstrap tooltip feature is a quick and easy process

Is there a way to turn off bootstrap tooltip on my website? I activated it with the code below: function activateTooltip() { const toolTips = document.querySelectorAll('.tooltip'); toolTips.forEach(t => { new bootstrap.Tooltip(t); } ...

Pressing the Add button will create a brand new Textarea

Is it possible for the "Add" button to create a new textarea in the form? I've been searching all day but haven't found any logic to make the "Add" function that generates a new textarea. h1,h2,h3,h4,h5,p,table {font-family: Calibri;} .content ...

Using JQuery to extract information from a JSON file

Here is the code I am working on, where I pass input username and password values. The function I have written checks if the input matches the data in a JSON file. If there is a match, an alert saying "login correct" will be displayed, otherwise it will di ...

Obtain a pointer to the timestamp within a embedded Kibana chart on an HTML webpage

The image at the specified link shows a black box labeled @timestamp displaying date and time information. Unfortunately, viewing the image requires a reputation of 10. Link to image: https://www.elastic.co/assets/bltde09cbafb09b7f08/Screen-Shot-2014-09-3 ...

Logging on the client side with node.js without the need for additional modules

Do you think it's a good idea to wrap my minified JavaScript code in a try-catch block so that if a client-side error occurs, it sends a POST request to my server and appends the error to a log file on the server? The main concern here is security - ...

Interact with Datatable by clicking on the table cell or any links within the cell

When I am working with the datatable, I want to be able to determine whether a click inside the table was made on a link or a cell. <td> Here is some text - <a href="mylink.html">mylink</a> </td> Here is how I initialize my da ...

Certain iFrame instances are unable to display specific cross-domain pages

I'm currently working on a project to create a website that can embed external cross-domain sites, essentially like building a browser within a browser. I've been experimenting with using iFrames for this purpose: While it works for some pages, ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

An issue arose when attempting to submit data from an AngularJS form

I am having an issue with my AngularJS form that is supposed to post data to a Scalatra servlet. Unfortunately, when the form is submitted, I am unable to retrieve any form parameters in my Scalatra servlet. Here is a snippet of my code: AngularJS $scop ...

Displaying HTML elements in a specific order using ng-repeat

Upon receiving the json message, my goal is to display it in HTML in a specific order. Within the json message, the position value indicates the desired order of elements, with 0 representing the first element in the array. At times, the json message may ...

Changing the Size of React Bootstrap Cards to Fit Your Grid Layout with Custom CSS

I am facing an issue with the varying sizes of react-bootstrap cards within a grid display. Check out the problem I am encountering: https://i.sstatic.net/szHjI.png I need the size of Over Under 0.5 card to be different from the one for Match Winner, as ...

The distinctions between routing and Ajax within AngularJS

Recently diving into the world of Angular, I find myself tackling the concept of routing. However, as I try to wrap my head around it, I can't help but notice its similarities with AJAX. Both seem to be about loading specific parts of HTML from a serv ...