Home > Blockchain >  How to insert today's date into Multiple Image URLs?
How to insert today's date into Multiple Image URLs?

Time:01-08

I have a same question but I have multiple image URLs: How to insert today's date into a IMAGE URL?

I have the image URL as follows:

<img src="https://www.example.com/2023/01/08/dl/01/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/02/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/03/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/04/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/05/image.jpg" alt="image"><br>

How do I insert today's date code on all the IMAGE URLs using javascript.

CodePudding user response:

Here is an example of how to add a date to each image:

const date = new Date();
const dd = String(date.getDate()).padStart(2, '0');
const mm = String(date.getMonth()   1).padStart(2, '0'); 
const yyyy = date.getFullYear();

const today = yyyy   '-'   mm   '-'   dd;

const images = document.querySelectorAll('img');
    
images.forEach(function(img) {
  img.src = img.src.replace(/.jpg/, '-'   today   '.jpg');
});

CodePudding user response:

here's the code.

const date = new Date();
const year = date.getFullYear();
let month = date.getMonth()   1;
month < 10 ? month = '0'   month : month;  
let day = date.getDate();
day < 10 ? day = '0'   day : day;  

const fullDate  = `${year}/${month}/${day}`;

let href = 'https://www.example.com/2023/01/08/dl/05/image.jpg';

var links = document.getElementsByClassName("img");

for(let i = 0; i < links.length; i  ) {
  links[i].setAttribute("src", `https://www.example.com/${fullDate}/dl/05/image.jpg`);
}
<!-- add a class to all of the images so you can access them with js -->

<!-- you may delete src attr -->

<img alt="image"  ><br>
<img alt="image" ><br>
<img alt="image" ><br>
<img alt="image" ><br>
<img alt="image" ><br>

CodePudding user response:

Here is the shortest way I can think of

String(i 1).padStart(2,'0') will create the 01, 02 etc

const yyyymmdd = new Date().toISOString().split('T')[0].split('-').join('/'); 
document.getElementById('imgContainer').innerHTML = Array.from({length:5})  // generate an array of 5
  .map((_,i) => `<img src="https://www.example.com/${yyyymmdd}/dl/${String(i 1).padStart(2,'0')}/image.jpg" alt="image" />`).join(`<br/>`)
<div id="imgContainer"></div>

Change the padStart if you have more than 99 images

CodePudding user response:

Make a function to add the date to a single element(from the question you linked). Put the image elements into an array using querySelecterAll().

Then do something like this

arrayOfImages.foreach((img) => addDateToImage(img))
  • Related