On the page, the calendar columns are displayed with abbreviations, such as "sat" instead of "saturday".
<div class="dayClass">sat, 14 may</div>
<div class="dayClass">sun, 15 may</div>
<div class="dayClass">mon, 16 may</div>
to be like below
<div class="dayClass">Saturday, 14 may</div>
<div class="dayClass">Sunday, 15 may</div>
<div class="dayClass">Monday, 16 may</div>
I wrote this code by searching
But I can’t just change the word "day" and the date will also be replaced
window.onload = function findAndReplaceDayName(){
var elements = document.querySelectorAll('.dayClass');
for ( var i=elements.length; i--; ) {
var text = elements[i].innerText;
if(text.slice(0,3) == 'sat' ){
elements[i].textContent = "Saturday"
}else if(text.slice(0,3) == 'sun'){
elements[i].textContent = "Sunday";
}else if(text.slice(0,3) == 'mon'){
elements[i].textContent = "Monday";
}}
But the result is this
<div class="dayClass">Saturday</div>
<div class="dayClass">Sunday</div>
<div class="dayClass">Monday</div>
Can you help me to change only the day and not the date.
Thankful
Footnote: I am new to both programming and English language
6
Answers
I appreciate your English as well as coding though you are a beginner.
There’s just a small change in your code that has to be made.
Like this :
By writing
elements[i].textContent = "Saturday"
you are replacing all of the textContent by ‘Saturday’. That’s why you lost all of the text.You sould replace only the first characters. So, by writing
elements[i].textContent = "Saturday"; elements[i].textContent += text.slice(3);
you’ll replace all the text by Saturday then you’ll add the next part to keep it.There is no need for any complex for loop.
Just use the build in forEach method.
As many other answers point out: you should replace a part of the string, keeping the rest intact.
Personally I’d avoid hardcoding those numbers, and would attempt to get the first part of the string up to the comma instead. Also, for systematic replacement of a small set of things, an object or an actual
Map
may be a good choice. And if you succumb to the dark side,replace()
can do the entire thing, as it can look for a regular expression, and then provide a replacement dynamically based on its findings:Here the
[^,]+
matches the non-comma characters from the start of the string, and then this match is going to be theday
argument for the arrow function, which simply looks up the corresponding long-name from themapping
object defined at the beginning.Here is a simple method – I am assuming there is always a match in fullNames.
If there is no way dayClass can start with anything else but day abbreviations, the code is even simpler