

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get odd and even position characters from a string?
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!
- Related Questions & Answers
- Converting Odd and Even-indexed characters in a string to uppercase/lowercase in JavaScript?
- Difference between sums of odd position and even position nodes of a Binary Tree in Java
- Java program to print odd and even number from a Java array.
- Even and Odd Components of a Signal
- How to get last 4 characters from string in C#?
- Java program to Print Odd and Even Number from an Array
- Even numbers at even index and odd numbers at odd index in C++
- Separate odd and even in JavaScript
- Signals and Systems: Even and Odd Signals
- Count Odd and Even numbers in a range from L to R in C++
- Sum of individual even and odd digits in a string number using JavaScript
- Missing even and odd elements from the given arrays in C++
- How to get last 2 characters from string in C# using Regex?
- MySQL query to get a single value from position of comma-separated string?
- How to extract characters from a string in R?
Advertisements