Hướng dẫn rotate string in javascript

Defining the algorithm, using the slice string method, the modulo operator and more.

Hướng dẫn rotate string in javascript

Photo by Mikael Kristenson on Unsplash

This article describes how to write a simple algorithm rotating a string. It also deals with the case of special characters taking two code units.

To understand how to compute the new string, check a few examples.

  • Rotating the string ABCDE to the left by 1 character results in BCDEA
  • Trying to rotate the same text by 2 characters results in CDEAB.

It is important to note what happens when trying to rotate with a number of characters greater than the string size. For example, rotating by 6 characters result in BCDEA, and rotating by 7 characters gives CDEAB

Rotating to Left

Now let’s try to implement such an algorithm and encapsulate it in a function.

function rotate(text, noOfChars = 0){
return text;
}

First, we need to detect the number of characters to rotate by. When the noOfChars is less than the size of the string then we have the value, but when the size of the text is lower than noOfChars we need to detect that number.

When you look at the result, rotating a string of 5 characters by 6 characters is the same as rotating it by 1 character. Rotating it by 7 characters is the same as rotating it by 2 characters. The number of characters to rotate by is in fact the modulo between the given number and the size of the string.

6 % 5 === 1
7 % 5 === 2

When you check the methods available for extracting part of a string you can choose between subtring, substr, and slice. I will go with slice but the same behavior can be accomplished with any of them.

The slice(start, end)method returns a portion of the string, starting at the given start index and ending before the end index. When extracting part of the string starting from 0 index, the specified number of characters is basically the end index.

"ABCDE".slice(0, 1)
//'A'
"ABCDE".slice(0, 2)
//'AB'

The second parameter is optional. When it is not specified slice extracts all the characters till the end of the string.

"ABCDE".slice(1)
//'BCDE'
"ABCDE".slice(2)
//'CDE'

Here is how our algorithm may look like.

function rotate(text, noOfChars = 0){
const n = noOfChars % text.length;
return text.slice(n) + text.slice(0, n);
}
rotate("ABCDE", 1)
//BCDEA
rotate("ABCDE", 2)
//CDEAB

Maybe is more clear if we write it using the template literal syntax.

function rotate(text, noOfChars = 0){
const n = noOfChars % text.length;
const part1 = text.slice(0, n);
const part2 = text.slice(n);
return `${part2}${part1}`;
}

Rotating to the Right

Rotating the text ABCDE to the right by 1 character results in EABCD

Rotating by 2 characters gives DEABC.

Rotating by 3 characters results in CDEAB.

Rotating by 4 characters gives BCDEA.

Rotating by 5 characters makes no change, it gives the same result as in the input text ABCDE.

Rotating by 6 characters is the same as rotating by 1 character. It gives EABCD.

Notice that rotating the text to the right gives the same result as rotating it to the left but with a different number of characters.

  • Rotating to the left with 1 gives the same result as rotating to the right with 4.
  • Rotating to the left by 2 characters is the same as rotating to the right by 3 characters.
  • Rotating to the left with 3 returns DEABC, the same as rotating to the right with 2.
  • Rotating to the left with 4 gives EABCD, the same as rotating to the right with 1

Rotating to right by n characters is the same as rotate to left by textSize — n characters.

function rotateRight(text, noOfChars = 0){
const n = noOfChars % text.length;
return rotate(text, text.length - n);
}
rotateRight("ABCDE", 1)
//EABCD
rotateRight("ABCDE", 2)
//DEABC

Dealing with Characters Taking Two Code Units

Sadly the previous solution does not work when dealing with characters taking two code units like an emoji. Check the next call.

rotate("😐ABC", 1)
//'�ABC�'

A possible solution is to convert the string to an array of characters, rotate the array, and then convert the result back to a new string. This is what the next function does.

function rotate(text, noOfChars = 0){
const chars = Array.from(text);
const n = noOfChars % chars.length;
const newArr = chars.slice(n).concat(chars.slice(0, n));
return newArr.join("");
}
rotate("😐ABC", 1)
//'ABC😐'

The Array.from utility can convert a string to an array of characters.

The slice array method works alike the slice string method. It extracts parts of the array into a new containing the elements between the given start and end indexes.

The concat array method concatenates two arrays into a new one containing the elements from both of them in order.

The join array method called with the empty string converts the new array of characters back into a new string.

Key Notes

  • slice method returns a new string, starting at the given start index and ending before the end index.
  • When we have to rotate a string by a number greater than the number of characters we need to divide it by the size of the text and use the remainder value. This can be accomplished with the modulo operator (%).
  • Rotating a string to the right by n characters is the same as rotating to the left by size — n characters.
  • When processing a string containing characters taking two code units we may need to convert it into an array of characters, process the array, and then convert the result back to a string.