1

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

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

3 Comments

You beat me to it! This is perfect.
How about an explanation so that the OP understands what's going on?
It would be less confusing to use "value" or currentValue (mdn) instead of "index" in the argument name, since it's not the array index.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.