Home > Net >  Moving the first character to the back of a string in Javascript
Moving the first character to the back of a string in Javascript

Time:11-25

I have been stuck trying to figure out this one part of my introduction to coding assignment. I know what it is asking but have no idea what the code is supposed to look like.

Define a function named Rotate that takes a string as input and returns a copy of that string in which all characters are rotated one position to the left. This means that the second character should be shifted from index 1 to index 0, the third character should be shifted from index 2 to index 1, and so on. The first character should be shifted so that it appears at the end of the string. For example, the function call Rotate('abcde') should return the string 'bcdea'. Insert this function definition into your string.js library file.

I know this code is probably dead wrong but the lecture slides my professor gave did not help at all.

function Rotate()
  
{
  var firstLetter; restString; end;
  
      firstLetter = str.charAt(0); 
      restString = str.substring(1,str.length); 
      end = restString.toLowerCase()   firstLetter.toLowerCase(); 

  return end;
}

CodePudding user response:

String can can understand like a array with each element is a character of string. So I recommned the solution for this problem as follows

function Rotate(str){
    return str.substring(1) str[0]
}

CodePudding user response:

Well, you need to pass in the argument str:

function Rotate(str) {
  var initial, rest;
  initial = str.charAt(0);
  // if you don't pass the second argument, you get everything up to the end of the string
  rest = str.substring(1);
  return rest   initial;
}

// please note you don't need separate var statements:
function Rotate(str) {
  var initial = str.charAt(0);
  var rest = str.substring(1);
  return rest   initial;
}

// or:
function Rotate(str) {
  // substring from the second char   substring of the first char
  return str.substring(1)   str.substring(0, 1);
}

// you could even extend Rotate to support multiple chars:
function Rotate(str, count) {
  if (count === undefined) count = 1;
  return str.substring(count)   str.substring(0, count);
}

  • Related