Rotate a string to the right in JavaScript
Intermediate · 3 min read
You may have seen a scrolling news ticker, where the text slides along and the letters that leave one end come back at the other. Underneath, that effect is a string rotation: take the last letter and move it to the front, again and again. In this tutorial you will write that rotation and watch the word javascript go all the way round.
You will write two functions. rotateRight(text) does one rotation. rotations(text) does one rotation per letter and collects every step in an array. You need to know what a string, an array and a for loop are. The string tools are explained below.
Cutting a string with slice
slice copies part of a string. You give it where to start and, optionally, where to stop. The stop position itself is not included.
const word = 'javascript';
console.log(word.slice(0, 4)); // java
console.log(word.slice(4)); // script
A negative number counts from the end. -1 means "one before the end", so:
const word = 'javascript';
console.log(word.slice(-1)); // t
console.log(word.slice(0, -1)); // javascrip
slice(-1) is the last letter. slice(0, -1) is everything except the last letter. Those two pieces are all the rotation needs. slice never changes the original string; it always returns a new one.
Here is the exercise. Try it yourself first if you like, or follow the steps.
5 Rotate a string one letter at a time
fairRotate the text javascript to the right by repeatedly taking the last letter and putting it at the front. Show each step.
Stuck? Three hints, smallest first
- 1. One rotation is
text.slice(-1) + text.slice(0, -1). - 2. After as many rotations as there are letters, you are back where you started.
- 3. The original animates this with a timer. Return the sequence instead, so it can be checked.
Step 1: one rotation
Put the last letter in front of the rest.
function rotateRight(text) {
return text.slice(-1) + text.slice(0, -1);
}
console.log(rotateRight('javascript')); // tjavascrip
console.log(rotateRight(rotateRight('javascript'))); // ptjavascri
The t moved to the front. Doing it twice moves the p in front of that.
Step 2: short strings
What about a single letter, or an empty string? Rotating 'a' should give 'a', and rotating '' should give ''. The Step 1 code happens to get both right, because the pieces are empty. It is still clearer to say so directly. A guard at the top returns the text unchanged when there is nothing to rotate:
function rotateRight(text) {
if (text.length < 2) return text;
return text.slice(-1) + text.slice(0, -1);
}
console.log(rotateRight('a')); // a
console.log(rotateRight('')); // prints an empty line
Anyone reading this later can see at once that short strings were thought about.
Step 3: collect every step
Now rotate again and again, keeping each result. Start with an empty array and a variable holding the current text. Each time round the loop, rotate the current text and push the result onto the array.
function rotations(text) {
const steps = [];
let current = text;
for (let i = 0; i < text.length; i++) {
current = rotateRight(current);
steps.push(current);
}
return steps;
}
current uses let because it changes on every pass. steps uses const because it is always the same array, even though items are added to it.
Step 4: run it
const steps = rotations('javascript');
for (const s of steps) console.log(s);
The output is ten lines, from tjavascrip down to javascript. The last line is the word you started with. A ten-letter word rotated ten times is back where it began, because every letter has moved to the front once. That gives you a quick way to check the code: the last step must equal the input.
console.log(steps.length); // 10
console.log(steps[steps.length - 1]); // javascript
Why return an array?
A ticker on a web page would use a timer, such as setInterval, to show one rotation every fraction of a second. You can't easily check something that only flashes on screen. Returning the list of steps lets you print them, test them and later feed them to a timer if you want the animation.
The full solution
The complete answer has both functions and prints all ten rotations. There is a comment at the end showing how a page would animate the same thing with setInterval. Press Run to see the output.
function rotateRight(text) {
if (text.length < 2) return text;
return text.slice(-1) + text.slice(0, -1);
}
function rotations(text) {
const steps = [];
let current = text;
for (let i = 0; i < text.length; i++) {
current = rotateRight(current);
steps.push(current);
}
return steps;
}
const steps = rotations('javascript');
for (const s of steps) console.log(s);
// The usual version uses setInterval to animate this in the page. Same sequence,
// but returning it means it can be asserted:
// setInterval(() => { el.textContent = rotateRight(el.textContent); }, 200);
Output
6 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 6 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('one rotation', rotateRight('javascript'), 'tjavascrip');
test('two rotations', rotateRight(rotateRight('javascript')), 'ptjavascri');
test('a full cycle returns to the start', steps[steps.length - 1], 'javascript');
test('there is one step per letter', steps.length, 10);
test('a single character is unchanged', rotateRight('a'), 'a');
test('empty text is unchanged', rotateRight(''), '');
slice(-1) takes the last character and slice(0, -1) takes everything but the last; together they are the whole rotation. The guard for length under 2 is not decoration — without it the empty string would still work by luck, but returning early makes the intent obvious. Rotating a ten-letter word ten times returns it exactly, which is what the third assertion pins down.
Common mistakes
- Mixing up
slice(-1)andslice(0, -1). The first is the last letter only, the second is everything but the last letter. Swapping them gives the wrong rotation. - Rotating the original text every time. If the loop calls
rotateRight(text)instead ofrotateRight(current), every step is the same. - Looping one time too few or too many. Use
i < text.length, so there is exactly one step per letter.
Try it yourself
- Write
rotateLeft(text), which moves the first letter to the end.rotateLeft('javascript')should giveavascriptj. - Add a second argument,
rotateBy(text, n), that rotates rightnplaces in one go usingslice(-n)andslice(0, -n). - What should
rotateBy('abc', 4)give? Use the%remainder operator so that largenworks.