简体   繁体   中英

How can I split a javascript array and replace elements of it?

updated I'm quite a new to this. I have looked everywhere and tried everything under the sun to fix this on my own. My data is from a text input where i need to read specific line. My code reads the lines perfectly using the slice(2,1) method. Now I need to use the data to do other things.

my extracted string from reading data lines from 3rd line data till 2nd last line, and this already works:

var x = readData.slice(2,-1).toString();

Output using console.log(x); //0 1,2 3,4 5 as it should be

but I want: '0,1','2,3','4,5'

So that i can use this data to do other things.

I have tried:

var x = readData.slice(2,-1).toString().split(' ',-1);

this gives me: [ '0', '1,2', '3,4', '5' ] //which is the closest

i have also tried:

var x = readData.slice(2,-1).toString().replace(/\s/g, ', ').split(" ", -1); which gives [ '0,', '1,2,', '3,4,', '5' ]

var x = [x.split(' ').join(',')]; which gives [ '0,1,2,3,4,5' ]

and a few other combos too. Can anyone please help?

According to the following statement

.replace(/\s/g, ', ').split(" ", -1); which gives [ '0,', '1,2,', '3,4,', '5' ]

in the question, this 0 1,2 3,4 5 is a string, so you can split by comma and then map the strings according to the desired output

 console.log("0 1,2 3,4 5".split(",").map(s => s.split(/\s+/g).join(",")));

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