Split the given string into arrays

Viewed 71

Suppose the given string is:

[[1]] is for cars, as [[2]] is for bikes

I want to split the string into an array of string using regex or any other way, when [[any number]] (for example: [[1]], [[2]]) is encountered.

[ 
   [[1]], 
   " is for cars, as ", 
   [[2]],
   " is for bikes"
]

What I have tried: 

"[[1]] is for cars, as [[2]] is for bikes".split(/\[\[(\d+)\]\]/gi);

This returns ",1, is for cars, as ,2, is for bikes"
2 Answers

Use positive lookbehind and positive lookahead

const myString = "[[1]] is for cars, as [[2]] is for bikes";
const output = myString.split(/(?<=\[\[\d+\]\])\s|\s(?=\[\[\d+\]\])/g);
console.log(output);

There are couple of issues in your code:

  1. .split is using capture group at wrong place i.e. you're capturing only digits instead of [[<digits>]]
  2. Since splitting pattern is found at the start as well so you will need to use .filter method to get rid of an empty string from the resulting array.

const str = "[[1]] is for cars, as [[2]] is for bikes";
var arr = str.split(/(\[\[\d+\]\])/gi).filter(Boolean);
console.log(arr);
/*
[
  "[[1]]",
  " is for cars, as ",
  "[[2]]",
  " is for bikes"
]
*/

Related