Hướng dẫn rotate string in javascript
Show Defining the algorithm, using the slice string method, the modulo operator and more.Photo by Mikael Kristenson on UnsplashThis 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.
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 Rotating to LeftNow let’s try to implement such an algorithm and encapsulate it in a function. function rotate(text, noOfChars = 0){ First, we need to detect the number of characters to rotate by. When the When you look at the result, rotating a string of 6 % 5 === 1 When you check the methods available for extracting part of a string you can choose between The "ABCDE".slice(0, 1) The second parameter is optional. When it is not specified "ABCDE".slice(1) Here is how our algorithm may look like. function rotate(text, noOfChars = 0){ Maybe is more clear if we write it using the template literal syntax. function rotate(text, noOfChars = 0){ Rotating to the RightRotating the text Rotating by Rotating by Rotating by Rotating by Rotating by 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 right by function rotateRight(text, noOfChars = 0){ Dealing with Characters Taking Two Code UnitsSadly the previous solution does not work when dealing with characters taking two code units like an emoji. Check the next call. rotate("😐ABC", 1) 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){ The The The The Key Notes
|