Click here to Skip to main content
15,913,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!


This is an exercise from W3resource. I am trying to work out the problem using my own thought logic.

The goal of the exercise is to keep removing the last letter in the word 'w3resource' and add it to the front of 'w3resource'. This is supposed to continue until you close the browser.

I am able to get it done, but when I reach the end of the array br, I get undefined. I then
tried set if(br || br[br.length-1]), but I guess array br is still empty so it can't go through
it again.

Using my code, can you please help me get the same effect as the original assignment:

JavaScript basic: Rotate a string from left to right - w3resource[^]



Here is my code:

function animate_string(word){


var br = word.split('');

if(br || br[br.length-1]){
setInterval(function(){
var show = br.pop() + br.slice(0).join('');
document.getElementById('target').innerHTML = show;}, 500);
}




}
animate_string('w3resource');

What I have tried:

I am able to get W3rescource to rotate once by removing the last letter and adding to the front of the text, but when it reaches the end of the 'array br', I get undefined. I then
tried set if(br || br[br.length-1]), but I guess array br is still empty so it can't go through
it again.
Posted
Updated 18-Jun-22 5:48am

Perhaps you're over-thinking things...
JavaScript
function animate_string(word) {
              setInterval(function () {
                 word = word.substring(word.length - 1) + word.substring(0, word.length - 1);
                 document.getElementById('target').innerHTML = word;
              }, 500);
}
animate_string('w3resource');
 
Share this answer
 
Comments
mappleleaf 25-Oct-17 12:16pm    
Thanks, you are star! You are correct, I was overthinking it.
const animateString = word => {
  word = word[word.length - 1] + word.slice(0, word.length - 1);
  return word;
};

console.log(animateString('w3resource'));
 
Share this answer
 
Comments
Richard Deeming 20-Jun-22 5:44am    
An unexplained code-dump which doesn't even attempt to answer the question is not sufficient reason to drag this already-solved question back into the active list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900