- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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!
- Related Articles
- Converting Odd and Even-indexed characters in a string to uppercase/lowercase in JavaScript?
- Swift Program to Get Odd and Even Numbers From the Array
- Swift Program to Get Odd and Even Numbers From the Array Using Library Function
- Difference between sums of odd position and even position nodes of a Binary Tree in Java
- How to get last 4 characters from string in C#?
- Java program to print odd and even number from a Java array.
- How to get last 2 characters from string in C# using Regex?
- Java program to Print Odd and Even Number from an Array
- Sum of individual even and odd digits in a string number using JavaScript
- MySQL query to get a single value from position of comma-separated string?
- How to extract characters from a string in R?
- How to Remove Characters from a String in Arduino?
- Count Odd and Even numbers in a range from L to R in C++
- Even and Odd Components of a Signal
- MySQL query to get a substring from a string except the last three characters?

Advertisements