Home > Software engineering >  Dynamically create HTML link for a specific date pattern in a URL
Dynamically create HTML link for a specific date pattern in a URL

Time:11-24

I need to create an dynamic link to to hyperlink a string so that anybody clicks on that string it opens the lin related to that day. For example if someone clicks today it will open this link. https://sobbanglay.com/sob/history-today-november-23/

Can you please help me to to create a simple script to create the above URL pattern dynamically?

I tried something like below, taking help from this forum but I am not able to print the month in string. Can you please help me to achive this is with simple html script like below?

<a href="https://sobbanglay.com/sob/history-today-january-01/" id="link">As it happened on today</a>

<script>
var d = new Date();
var month = d.getMonth()  1;

var day = d.getDate();


document.getElementById("link").href = "https://sobbanglay.com/sob/history-today-"   month   "-"   day   "/";
</script>

CodePudding user response:

As you can see, if u press the link you will get the month (11), but if u want November, you can try to make a switch case (just make all the cases)

<a href="https://sobbanglay.com/sob/history-today-january-01/" id="link">As it happened on today</a><script>
var monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];



var d = new Date();
let month = monthNames[d.getMonth()];
var day = d.getDate();



document.getElementById("link").href = "https://sobbanglay.com/sob/history-today-"   month   "-"   day   "/";
</script>

I know is not the best answer but it works.

CodePudding user response:

<script> 
const months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December"];
const days= ["Sun","Mon", "Tue","Wed","Thurs","Fri","Sat"];
var d = new Date();
var month = d.getMonth();
var day = d.getDay();
var year=d.getFullYear();
document.getElementById("link").href=`https://sobbanglay.com/sob/history-${days[month]}-${months[month]}-${year}`;
</script>
  • Related