简体   繁体   中英

JavaScript string into multidimensional array

I'm passing myself a string of results from php by ajax that I would like to put into a two dimensional array in JavaScript

The string looks like: value1^*value2^*value3^*value4***value1^*value2^*value3^*value4

I would like to split the values by '^*' into the first row of the dimensional array, then the next row would be after the '***'

Desired array: var Text = [['value1', 'value2','value3','value4'],[value1','value2','value3','value4']];

You can use split() to split your string into an array of strings ( value1^*value2^*value3^*value4 and value1^*value2^*value3^*value4 ), after that you will need map() to creates a new arrays inside each array which we get before.

Example:

 var str = "value1^*value2^*value3^*value4***value1^*value2^*value3^*value4" str = str.split('***') str = str.map((value) => value.split('^*')) console.log(str) 

You can do something like that

 var input = "value1^*value2^*value3^*value4***value5^*value6^*value7^*value8"; var res = input.split('***').map(function(rowValues){ return rowValues.split('^*'); }) console.log(res); 

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