0

I'd like to be able to split up a string based on a substring delimiter, starting the split before the first character of the delimiter substring. Currently:

var string = "choc: 123 choc: 328 choc: 129";
string.split("choc");

Will give me ["", ":123 ", ": 328", ": 129"], but I am looking to get ["choc: 123 ", "choc: 328", "choc: 129"], instead.

njp
  • 695
  • 2
  • 8
  • 21
  • 3
    Possible duplicate of [Split String in Javascript but keep delimiter /](https://stackoverflow.com/questions/36464953/split-string-in-javascript-but-keep-delimiter) and [Javascript split string by another string and include that another string that was used to split it into result](https://stackoverflow.com/questions/45109097) and [Split string into array without deleting delimiter?](https://stackoverflow.com/questions/24503827) and [JS string.split() without removing the delimiters](https://stackoverflow.com/questions/4514144) – adiga Feb 13 '19 at 13:08
  • Learn about Regex, that's all you need to know – Vencovsky Feb 13 '19 at 13:09
  • Why not match instead of split to begin with in such a case? (Assuming the discrepancy between `choc: 123 ` and `choc: 328`, one with trailing slash, the other without, is just negligence during posting, and not the actual requirement.) – 04FS Feb 13 '19 at 13:14

2 Answers2

4

You could take a positive lookahead.

var string = "choc: 123 choc: 328 choc: 129";
console.log(string.split(/(?=choc)/));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can do it with a positive lookahead as @Nina Scholz said, and add \s* before the lookahead to remove any leading space before choc:

const string = 'choc: 123 choc: 328 choc: 129';
const result = string.split(/\s*(?=choc)/);

console.log(result);
jo_va
  • 13,504
  • 3
  • 23
  • 47