Jeff Spicoli Jeff Spicoli - 5 months ago 19
Javascript Question

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

Answer

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)