0

I need to split a string by a delimiter so that it becomes 2 arrays. Here is an example of string "55,56,*,51,52".

I want to end up with [["55","56],["51","52"]] I have trie with split() in javascript to no avail- I believe I need a regex solution, which I do not know how to do.

if the string to process looks like this ",*,51,52" it should return [[],["51,"52"]]
if it looks like "51,*," it should return [["51"],[]]
and ",*," should return [[],[]] -

Is this possible?

Thanks.

2 Answers 2

3

You can do this via the string.split method:

var str = "55,56,*,51,52".split('*');
for (var i=0;i<str.length;i++) str[i] = str[i].split(',');
//str now contains [["55", "56", ""], ["", "51", "52"]]

You can change your string to "55,56*51,52" to get the result of [["55","56],["51","52"]].

Alternatively, you can also do it the slightly longer way:

var str = "55,56,*,51,52".split('*');
for (var i=0;i<str.length;i++) {
    str[i] = str[i].split(',');
    for (var n=0;n<str[i].length;n++)
        !str[i][n] && str[i].splice(n,1);
}
//str now contains [["55","56],["51","52"]]

Then it will work with the commas around the asterisk.

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

3 Comments

you could also just use regex to look for a , either at start or end of string and remove it.
If the split method will take a regex, those comma's could be stripped in the first split with ,?\*,?
Or a non-regex ,*, if the OP is sure it is always that form.
0

Here is a shorter version without using split:

function twoArrays(str) {
  return JSON.parse(("[[" + str + "]]").replace(/,\*,/g, "],["));
}

// Examples:
twoArrays("55,56,*,51,52") // => [[55,56],[51,52]]
twoArrays("55,56,*,")      // => [[55,56],[]]
twoArrays(",*,")           // => [[],[]]

2 Comments

I get an error when I try this: SyntaxError: Unexpected token * . Am I not designating the delimiter correctly?
This worked great and is shorter than the first answer, which also worked well. Thanks!

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.