0

I want to split a string in a bidimensional array.

My array is like this one:

var str = 'a) first sentence without fixed lenght b) second phrase c) bla bla bla'

The returning array that i need is like:

var arr =[
          [ 'a', 'first sentence without fixed lenght' ],
          [ 'b', 'second phrase' ],
          [ 'c', 'bla bla bla' ]
         ];

I thought about use a regular expression to find the index of the list something like this:

/\w\)\s/gi

and then split the string, but without success. Anyone could help me?

2 Answers 2

1

Okay you can do this with a split or match. I went for a solution not counting on ) always being a delimiter. Instead I am looking for a very specific pattern of whitespace,letter,),whitespace in a zero-length lookahead. So most probable uses of parenthesis like "D) (whispers)" will be okay [ D) matches s) does not ].

var str = 'a) first sentence without fixed lenght b) second phrase c) bla bla bla';
var re = /(?=\s\w\)\s)/g;
var myArray = str.split(re);
var text;
var parenIndex;
// the result is = myArray[ 'a) first ...', 'b) second ... ', 'c) third ...' ];

for (var i = 0, il = myArray.length; i < il; i++) {
    text = myArray[i];
    parenIndex = text.indexOf(')'); // get first instance of )
    myArray[i] = [ text.substring(0, parenIndex - 1), text.substring(parenIndex + 1) ];
}
// the result is = myArray[ ['a', 'first ...'], ['b', 'second ... '], ... ];

A simpler less reliable approach would as follows. It assumes that ) is always a delimeter.

var str = 'a) first sentence without fixed lenght b) second phrase c) bla bla bla';
var re = /(?=\w\))|\)/g;
var myArray = str.split(re);
var newArray = new Array(myArray.length / 2);

for (var i = 0, il = myArray.length; i < il; i += 2) {
    newArray[i / 2] = [ myArray[i], myArray[i + 1] ];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your second approach, it works perfectly but in the line 3 the correct syntax is: str.split(re); the for is: for(var i=0 and there is a close parenthesis to add in the following line.. ;) I added also a trim() when I store the vars in the array.
1

here's a simple way to pull it off:

var ray= 'a) first sentence without fixed lenght b) second phrase c) bla bla bla'
.split(/(\w)\) /)
.slice(1)
.map(function(a,b,c){if(b%2){ return [c[b-1],a] }})
.filter(Boolean);

alert(JSON.stringify(ray, null, "\t"));

   /* shows: 
 [
    [
        "a",
        "first sentence without fixed lenght "
    ],
    [
        "b",
        "second phrase "
    ],
    [
        "c",
        "bla bla bla"
    ]
]
*/

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.