Michel
Michel

Reputation: 4157

Split string with regex, keep delimiter at start of line

I need to break a string:

Examples:

Hello,_have a beer_or a sandwich.$Bye  =>  Hello,
                                           _have a beer
                                           _or a sandwich.
                                           *Bye

$Hello,_have a beer,$or a sandwich.*Bye  => $Hello,
                                           _have a beer,
                                           $or a sandwich.
                                           *Bye

I came up with this regex:

/_.*?(?=[_\*\$])|\*.*?(?=[_\*\$])|\$.*?(?=[_\*\$])/g

The problem is:

  1. It doesn't capture the first part of the string when that part doesn't
    start with * _ $. (In the first example Hello is not included.)
  2. It does not capture the last part of the string, because the next
    character is not * _ $. (in both examples *Bye is not included)

I've tried adding ^.*?(?=[_\*\$]) for the first part, but then parts starting with * _ $ don't get selected.

A fiddle

Upvotes: 3

Views: 47

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a positive lookeahead with the wanted chracters for splitting.

var string = '$Hello,_have a beer,$or a sandwich.*Bye_ ',
    splitted = string.split(/(?=[$_*])/);
    
console.log(splitted);

Upvotes: 2

Related Questions