Regex Replace will only make changes to the final match found

My goal is to change the src of multiple image HTML elements in plain text (before they show up in the browser).

Here's my current progress:

var base = './images';
        
var sample = '<p><img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-2"></p><p><img src="3.png" alt="image-3"></p>';
        
sample = sample.replace(/(<img.+src=")(?!http:\/\/)(.*?)"/g, '$1' + base + '/$2"');
        
$('pre').text(sample);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

However, it seems to only replace the src of the last image element. What am I overlooking?

Answer №1

The regex pattern <img.+src is currently greedy, capturing everything between the first occurrence of img and the last occurrence of src. To make it non-greedy, you can modify your code as follows:

<img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img src="

Replace the greedy match with a non-greedy match:

sample = sample.replace(/(<img.+?src=")(?!http:\/\/)(.*?)"/g, '$1' + base + '/$2"');

var base = './images';
        
var sample = '<p><img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img src="3.png" alt="image-1"></p>';
        
sample = sample.replace(/(<img.+?src=")(?!http:\/\/)(.*?)"/g, '$1' + base + '/$2"');
        
$('pre').text(sample);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

Answer №2

According to a comment by @elclanrs, it appears that the current approach being used may not be the most suitable. Modifying it via the DOM with jQuery or similar methods might be more appropriate.

However, if for some reason this method is deemed necessary (considering all factors are not known), then the issue can possibly be resolved by refining the RegEx pattern. Using greedy matching typically yields better performance, and resorting to lazy evaluation (non-greedy) often indicates either insufficient specificity in the RegEx or using RegEx for a problem that doesn't require it. The following code snippet could help address the situation:

var base = './images';
        
var sample = '<p><img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img alt="image-1" src="3.png"></p>';
        
sample = sample.replace(/(<img[^>]+src=")(?!http:\/\/)([^"]+)"/g, '$1' + base + '/$2"');
        
$('pre').text(sample);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

I'm still getting accustomed to using the code tags correctly. Continuous learning process!

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

Delay the execution of the callback function until the promise has been fulfilled

I am facing an issue with a third-party library that I am listening to for events. When I try to modify the data it appends to the UI synchronously, everything works perfectly. However, once I introduce Ajax callbacks or promises into the mix, the function ...

XMLHTTP communication issue between JavaScript and Node.js

I have a request from an HTML page to a Node service. The service functions perfectly in Firefox and Chrome when accessed through the URL. It also works flawlessly when I use curl and Postman. However, when using XMLhttpsRequest, it triggers an error eve ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Error occurs when ASP.NET application is executed due to `Sys` being undefined

Currently, I am working on developing a Web Application using WebForms with ASP.NET. One of the functionalities involves loading a custom javascript script file through a ScriptManager. However, upon viewing the page in a browser, I am encountering an iss ...

"The Vue component's data is successfully updating within a method using setInterval(), however, the changes are not reflected in the DOM

I have a function in my methods that gets triggered with a @click in the view. The function starts a timer, and although it seems to work fine in the DevTools, the timer only updates in the DevTools when I refresh the page. Moreover, in the view, the time ...

What is the best way to retrieve comprehensive information from an API?

I have a task to complete - I need to retrieve data from the Pokemon API and display it on a website. This includes showing the name, HP, attack, defense stats of a Pokemon, as well as the Pokemon it evolves into. The challenge I'm facing is obtaining ...

Are there distinctions between using app.use("/", express.static) versus app.use(express.static)?

Is there a distinction between the following scenarios, assuming we have already executed app.set('thePath', thePath)? app.use('/', express.static(thePath)) app.use(express.static(thePath)) app.use(express.static(app.get('thePath ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Avoid page refreshing when modifying app.js in React

Today is only my second day using React and I started by creating a React app with "npx create-react-app." However, when I tried to make changes to the app.js file, they didn't appear on the page even after refreshing the browser multiple times. (My n ...

What is causing the repetition of values in the output from my .ajax() request?

I'm feeling lost with my code snippet. I am attempting to display values from a json request using .ajax(). Here is the code causing trouble: $.each(posts, function(k, v){ $("section ul").append("<li><p>" + v.webTitle + "</p>&l ...

Enrich your HTML using AngularJS

CSS <div class="container"> <section> <p>{{content}}</p> </section> </div> script.js (function () { var script = function ($scope){ $scope.content = "example"; } }()); I am currently ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

React Navigation Error: navigateTo must be used within a valid router configuration

When attempting to utilize useNavigation() from react-router-dom, I encounter the following error: Error: useNavigation must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router. NavBar src/components/NavBar.js:6 3 ...

Send data to a JavaScript file

Even though this particular question has been asked and answered multiple times, I am still struggling to find a solution to my problem. I am currently working with Masterpages and JavaScript files, and as many people are aware, Masterpages can be quite t ...

Convert the excel file containing nested cells, including headers, into a JSON format

I am looking for a way to import data from an Excel file, convert it to JSON, and display the same table in my form. Although I have tried using XLSX and XLSX.utils.sheet_to_json(sheet,{header: 1, defval: ''}), I'm facing difficulties with ...

Seeking a way to display a random div at a 1% rate without generating additional div elements

Searching for an answer to display only one div with a rate of 1/100. Currently, I am utilizing the following JavaScript: var random = Math.floor(Math.random() * $('.item').length); $('.item').hide().eq(random).show(); This method wor ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

"Communication breakdown in Vue.js: $emit event not being picked up by corresponding $

Vue.component('rating-edit', { template:` <form> <input v-model="rating.title" type="text"> <textarea v-model="rating.remark">{{rating.remark}}</textarea> <button type="button" @click=" ...