I am trying to develop a function inside an external Javascript file that I can later call/use inside an HTML file. I need this function to take a string and shift the individual characters over one, I.E the string "ABCDE" would become "BCDEA" after going through the function. But instead of that specific string, I would like to be able to use a string variable named "key", since the string that needs to be shifted can be whatever the user enters for it. I am completely lost and unsure of what to do so any help would be appreciated.
The only thing I can think of possibly doing is subtracting the index of the first character in the string by one, so it would be -1 resulting in the code thinking that it is at the back of the string since the last character is assigned -1 but I don't know if it will even work, or how to set it up if it did.
CodePudding user response:
You can shift a string using the following function that uses simple substring()
manipulation which is a function you can call on all strings:
function shiftString(str, shift) {
return str.substring(shift) str.substring(0, shift);
}
Running for instance shiftString("ABCDE", 2)
will result in "CDEAB"
, since:
str.substring(2) == "CDE"
(take all characters from the second index onward; strings are zero-indexed)str.substring(0, 2) == "AB"
(take the 0-th index until the second index)