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

Perform shifting within a string in JavaScript

王林
Release: 2023-08-26 10:41:13
forward
1506 people have browsed it

在 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]];
Copy after login

then the output should be -

const output = 'cab';
Copy after login

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));
Copy after login

Output

The output in the console will be -

cab
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template