How to get odd and even position characters from a string?

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function that removes every second character (starting from the very first character) from a string and appends all of those removed characters at the end in JavaScript.

For example −

If the string is "This is a test!"
Then it should become "hsi etTi sats!"

Therefore, let’s write the code for this function −

Example

const string = 'This is a test!';
const separateString = (str) => {
   const { first, second } = [...str].reduce((acc, val, ind) => {
      const { first, second } = acc;
      return {
         first: ind % 2 === 1 ? first+val : first,
         second: ind % 2 === 0 ? second+val : second
      };
   }, {
      first: '',
      second: ''
   })
   return first+second;
};
console.log(separateString(string));

Output

The output in the console will be −

hsi etTi sats!
raja
Published on 24-Aug-2020 13:13:36
Advertisements