DEV Community

Kevin Kim
Kevin Kim

Posted on

How to Rotate a String in JavaScript

Recently, I applied a job in a certain company that was hiring a React developer. I sent my CV, did a coding assessment and passed. After this I was invited for an in-person interview where I was required to write code on paper.

The coding problem was: write code in the programming language of your choice that rotates a given string a specified number of times.

At first I freaked out as I had not tackled such a problem before, keep in mind that I am not a guru. I took the pen and paper and started writing code.

After struggling for a few minutes, I was able to write code for positive number rotation but I didn't know that they also required the code to also handle negative number rotation and my time was up.

Anyway, I was able to solve the negative rotation part in my mind on my way home and I want to share it here in case you ever encounter such a problem.

Here's is the JS code to rotate a string(handles both left and right rotation):

const rotate = (text, n) => {
  txtArr = text.split("") 

    for(let i = 1; i<=n; i++){
      let firstel = txtArr[0]
  else if(n<0){
    for(let i = -1; i>=n; i--){
      let lastel = txtArr[txtArr.length-1]


rotate("hello", -2)
Enter fullscreen mode Exit fullscreen mode

Code explanation:

I will explain the code with the steps involved:

  1. Convert the text into an array using the text.split() method.
  2. Use an if statement to check whether n is positive, n>0.
  3. If n is positive:
  • use a for loop to loop through the textArr n times.

  • get the first element in the array using txtArr[0]

  • Remove the first array element using txtArr.shift()

  • Add the first array element to the end of the aaray using txtArr.push(firstel)

4.If n is negative:

  • use a for loop to loop through the textArr n times.

  • get the last element in the array using txtArr[txtArr.length - 1]

  • Remove the last array element using txtArr.pop()

  • Add the last array element to the beginning of the aaray using txtArr.unshift(lastel)

5.If n is equal to 0, return it as it is


That's all for this article. Hope you learn a thing or two. See you in the next one :)

Top comments (0)