![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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!
Advertisements