TimP
TimP

Reputation: 37

Split string in two strings by possition

So I'm trying to split a string to in two different strings

I want to make a function that will take first letter from the string and push it to another string, then take second letter and push it to another string, then restart the loop and start from the place it stopped

Example:

imagine i have this string let string = ['SOMEMESSAGE'];

and i want it to be like this:

let firtsLetters = ['SMMSAE'];
let secondLetters= ['OEESG'];

Upvotes: 0

Views: 37

Answers (2)

Dumal Aluthdeniya
Dumal Aluthdeniya

Reputation: 163

As you mentioned your string is an array of strings. Like this

let text = ['SOMEMESSAGE', 'MYNAME'];

If you want to loop through an arrays of strings you can use following.

let text = ['SOMEMESSAGE', 'MYNAME'];

            let arrya1 = [];
            let array2 = [];

            text.forEach((ch,i)=>
            {
                x = 0;
                for(var n of ch) {
                     (x % 2 == 0) ? arrya1.push(ch.charAt(x)) : array2.push(ch.charAt(x))
                     x++;
                }
            });

             const firstLetters = arrya1.join('');
             const secondLetters = array2.join('');

    console.log(text);
    console.log(firstLetters);
    console.log(secondLetters);

Upvotes: 0

kind user
kind user

Reputation: 41913

You could for example split the string into an array, thenArray#filter over it, according to the index of currently looped element. Then - join the array to get the string.

const string = 'SOMEMESSAGE';

const firstLetters = [...string].filter((_, i) => !(i % 2)).join('');
const secondLetters = [...string].filter((_, i) => i % 2).join('');

console.log(firstLetters);
console.log(secondLetters);

Upvotes: 2

Related Questions