15/03/2024 Is t" /> 15/03/2024 Is t" /> 15/03/2024 Is t"/>

Replace nth-occurence of a string with an html tag

33 views Asked by At

I am trying to replace the second / of the following string with a
tag so that the year will break line

<span class="post-date">15/03/2024</span>

Is there any way to replace a character(or string in general) with an html tag, like the <br> tag?

1

There are 1 answers

1
sabarish On

i think this will work

 <span class="post-date" id="post-date">15/03/2024</span>

<script>
var dateString = document.getElementById("post-date").innerHTML;
var secondSlashIndex = dateString.indexOf('/', dateString.indexOf('/') + 1);
var firstPart = dateString.substring(0, secondSlashIndex);
var secondPart = dateString.substring(secondSlashIndex + 1);
var replacedString = firstPart + "<br>" + secondPart;
document.getElementById("post-date").innerHTML = replacedString;
</script>