Update the src attribute of img elements using regular expressions

Figured it out in case anyone might find it useful, here's the solution:

var feed      =   feeds.entries[i].content;
var parsedFeed    =   feed.replace(/src=/gi, "tempsrc=");
var tmpHolder =   document.createElement('div');
tmpHolder.innerHTML=parsedFeed;

I have a string that includes HTML markup with <img src='path.jpg'/>

I want to use a regex on the string to change every src attribute to tmpSrc

so

 <img src='path.jpg'/>

would be transformed into

 <img tmpSrc='path.jpg'/>

This is specifically for JavaScript

Here's the original issue posted elsewhere but still unresolved:

Browser parse HTML for jQuery without loading resources

How to parse AJAX response without loading resources?

Thanks

Answer №1

If you have full control over the string and it is not extracted from an external web page, using a regular expression is safe. To substitute all instances of <img src= with <img tmpSrc=, you can execute the following operation:

var str = "<img src='path.jpg'/>";   // Your source string
str = str.replace(/<img src=/gi, "<img tempSrc=");

Some users caution against using regex on HTML content fetched from a webpage due to variations in HTML structures across browsers. However, if the string being manipulated is within your purview and its format is predictable, this regex method should function without issue.

Answer №2

Attempting to modify HTML using Regular Expressions can lead to mistakes.

If you are willing to use jQuery on your website:

$('img').each(function() {
    var src = this.src;
    $(this).attr('tmpSrc', src).removeAttr(src);
});

Answer №3

function updateImages() {
    var allImages = document.getElementsByTagName('img'),
        source,
        total,
        index;

    for (index = 0, total = allImages.length; index < total; index++) {
       source = allImages[index].getAttribute('src');
       allImages[index].setAttribute('dataSrc', source);
       allImages[index].removeAttribute('src');
    }
}

Answer №4

String Transformation:

originalInput = "<img src='path.jpg'/>";
modifiedOutput = originalInput.replace("src","tempSource"); 

DOM Manipulation:

    imageElement = document.getElementById("theImage");  
    imageElement.tempSource = imageElement.src;
    imageElement.removeAttribute("src");

Answer №5

Take a look at this informative article discussing the challenges of using regex to parse HTML. It can be quite complex and may not be the best solution. Finding a foolproof method seems unlikely.

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

Save the value of a promise in a variable for future use in state management within a React-Native application

let storage = AsyncStorage.getItem('@location_data').then(data => data) const MainApp = () => { let [currentLocation, setCurrentLocation] = useState(storage); The current situation is that the storage variable holds a promise. How can ...

How can I retrieve the value of $_POST[] immediately after a selection is made in a dropdown box

Is there a way to retrieve the $_POST value immediately after changing the select option without having to submit the form? <select name="cat_id" class="form-control" onChange="this.form.submit();" style="width:300px;"> <?php ...

Using jquery to dynamically retrieve the unique property identifier

I have a dynamically generated table with a button labeled as view images. Each time this button is clicked, I need to retrieve the image names from the database for that specific property. <?php foreach($unapproved as $unapp):?> < ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Accessing multi-dimensional array properties in PHP with JavaScript integration

In my PHP code, I have an array structured like this: <?php $data = array(); $data[0] = array('year' => 2001, 'month' => array( 'January' => array('val1' => 1000, 'v ...

I am having trouble understanding why my JavaScript code is bypassing the if statements

let emptyErr = [] if (!(req.body.title)) { emptyErr[0] = ('A title must be provided for a post!') } else if (!req.body.category) { emptyErr[1] = ('Please select a category for your post.') } else if (!req.body.content) { ...

The essential criteria for script tag and page validation requirements

There are instances where I have pages that contain only a script without any content (such as sending data through postMessage and then closing itself). In these cases, is the page considered valid with just <script>doSomeStuff</script> or do ...

Avoid triggering a second event: click versus changing the URL hash

One of the pages on my website has tabs that load dynamic content: HTML <ul> <li><a href="#tab-1">TAB 1</li> <li><a href="#tab-2">TAB 2</li> <li><a href="#tab-3">TAB 3</li> </ul&g ...

Generate pre-set components using fundamental building blocks

Can I predefine some props for components? In my Vuetify example, let's say I want to customize the v-btn component with specific props. This custom implementation would act as a child component while still providing all the functionalities of the par ...

What is the process for generating an array of arrays in a React component?

I'm currently working on developing a word-guessing game similar to Wordle using React. The interesting twist in this game is that players have the ability to choose both the number of attempts allowed and the length of the word they are trying to gue ...

Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text? $('textarea').on('input', function() { var scrollHeight = parseInt($(this).prop('scrollHeight&apos ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

How to launch a new window for a popup

How can I make IE8 open new windows as pop-ups without changing browser settings? I want to use JavaScript's window.open() function. Firefox opens new windows correctly, but IE8 opens them in tabs instead of pop-up windows. Any suggestions on how to a ...

I'm curious, are there any html rendering engines that can display text-based content using curl-php?

When utilizing PHP cURL to interact with webpages, I often find myself needing to use regular expressions if the page contains AJAX and JavaScript elements. Does anyone have any recommendations for rendering HTML pages and extracting the text-based render ...

Dropdown Box Linking and Input Field Integration in HTML

I have a scenario where students need to pay monthly fees for their classes. My objective is as follows: 1. Dropdown #1: Student Names 2. Dropdown #2: Month Names 3. Textbox: Fees amount for the selected month The code I am using: $(document).ready(fu ...

Tips for handling Promise.all and waiting for all promises to resolve in an async function in Express JS

I'm relatively new to JavaScript and especially asynchronous programming. My current project involves creating an Express+React application that shows a GitHub user's information, including a few repositories with the latest 5 commits for each. ...

Posts that are repeated when making an AJAX call in WordPress

I have been experimenting with implementing a 'load more' button feature in my WordPress site. The concept is simple - users click the button, and additional posts are loaded using AJAX without the need for page reload or pagination. Following a ...

Can orbit controls be tweened in three.js?

When utilizing the TWEEN function within three.js, I have noticed that it is mainly used for tweening objects. Although I can successfully tween the camera's position, I am looking to also tween the orbit control to mimic following a target while the ...

Integrating external JavaScript widgets into the web application in real-time

I am currently engaged in a React js project that involves the dynamic addition of third party scripts (widgets) to the web app. These widgets encompass various third party platforms such as Twitter, Instagram, Youplay, Youtube, and more. The existing co ...

Switch up div containers with JavaScript based on the set array order of elements?

As I work on creating a list that calculates the sum of selected numbers, I encountered an issue with rearranging the items. Despite successful functionalities like adding images with names, changing languages, and performing calculations, the page keeps r ...