I’m new to coding.
I want to write a JS program to rotate a string (in the right direction) periodically by removing the last character every time and attaching it to the front. But when I run my code, a whole line or the whole page will be filled with the string. What’s wrong with my code?
I defined a function that: 1. stores the content of an HTML p element in a variable; 2. changes the value of the variable to a new string with the last character of the original string attached to its front; 3. changes the content of the p element into the new string, and 4. repeats this process using the setInterval method.
function animation() {
var text = document.getElementsByTagName("p")[0].innerHTML;
setInterval(function() {
text = text.substring(text.length - 1, 0) + text.substring(0, text.length - 2);
document.getElementsByTagName("p")[0].innerHTML = text;
}, 100);
}
<body onload="animation()">
<p>JavaScript</p>
</body>
4
Answers
I think the issue might be with your substring indexing. You reference
substring(text.length - 1, 0)
, which returns the string from the second-to-last character to the first character. It seems that you want only the last character, which would besubstring(text.length - 1, text.length)
.I also changed
text.substring(0, text.length - 2)
totext.substring(0, text.length - 1)
because you seem to want the entire string minus the last character, not minus the last two characters.Does this achieve your goal?
For reference, substring (MDN) works like this:
You aren’t reading the value of the previous rotation. Here’s a clearer working version:
I believe your problem is just a slight misunderstanding in how the substring functions works:
text.substring(text.length - 1, 0)
doesn’t necessarily make much sense because the start point is after the end point. In this case it just ends up being equivalent totext.substring(0, text.length - 1)
which explains why your text keeps getting larger and larger.Replacing
text.substring(text.length - 1, 0)
withtext.substring(text.length - 1, text.length)
should do the trick, and hopefully it’s obvious why this gets the last letter. Also, the end index is non-inclusive, meaning the substring doesn’t include the character at the index, so you’ll want to replacetext.substring(0, text.length - 2)
withtext.substring(0, text.length - 1)
As a side note, instead of using
text.substring(text.length - 1, text.length)
to get the last character, you could just usetext[text.length - 1]
to get it, which I think is a bit cleaner.Here’s a working code snippet with the changes mentioned:
To make sure you get how everything works I would try and see if you can get it to roll/rotate the other way
a better way to do it is by using array of chars: