简体   繁体   中英

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'];

You could for example split the string into an array, then Array#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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM