Home  >  Article  >  Web Front-end  >  Perform shifting within a string in JavaScript

Perform shifting within a string in JavaScript

王林
王林forward
2023-08-26 10:41:131467browse

在 JavaScript 中执行字符串内的移位

Suppose we have a string str containing lowercase English letters and an array arr, where arr[i] = [direction, amount] −

  • direction can be 0 (shift left) or 1 (shift right).

  • amount is the amount by which the string s is to be moved.

  • Shifting left by 1 means removing the first character of s and appending it to the end.

  • Similarly, shifting right by 1 means removing the first character of s and appending it to the end. Remove the last character of s and add it to the beginning.

We need to write a JavaScript function that accepts a string as the first parameter and an array data containing shift as the second parameter.

The function should iterate over the array and perform the necessary shifts in the string and finally return the new string.

For example -

If the input string and array is -

const str = 'abc';
const arr = [[0, 1], [1, 2]];

then the output should be -

const output = 'cab';

Because,

[ 0,1] means move 1 to the left. "abc" -> "bca"

[1,2] means move 2 to the right. "bca" -> "cab"

Example

The code is -

Live Demo

const str = 'abc';
const arr = [[0, 1], [1, 2]];
const performShifts = (str = '', arr = []) => {
   if(str.length < 2){
      return str;
   };
   let right = 0
   let left = 0;
   for(let sub of arr){
      if(sub[0] == 0){
         left += sub[1];
      }else{
         right += sub[1];
      };
   };
   if(right === left){
      return str;
   }
   if(right > left){
      right = right - left;
      right = right % str.length;
      return str.substring(str.length - right) + str.substring(0,
      str.length - right);
   }else{
      left = left - right;
      left = left % str.length;
      return str.substring(left) + str.substring(0,left);
   };
};
console.log(performShifts(str, arr));

Output

The output in the console will be -

cab

The above is the detailed content of Perform shifting within a string in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete