Cmag
Cmag

Reputation: 15750

Split string with various delimiters while keeping delimiters

I have the following string:

"dogs@cats^horses^fish!birds"

How can I get the following array back?

['dogs','@cats','^horses','^fish','!birds']

Essentially I am trying to split the string while keeping the delimeters. I've tried string.match with no avail.

Upvotes: 0

Views: 50

Answers (2)

MDEV
MDEV

Reputation: 10838

This does what you want:

str.match(/((^|[^\w])\w+)/g)

Without more test cases though, it's hard to say how reliable it would be.

This is also assuming a large set of possible delimiters. If it's a small fixed amount, Samer's solution would be a good way to go

Upvotes: 2

Samer
Samer

Reputation: 988

Assuming those are your only separators then you can do this:

var string = "dogs@cats^horses^fish!birds";
string.replace(/(@|\^|!)/g, '|$1').split('|');

We basically add our own separator, in this case | and split it based on that.

Upvotes: 4

Related Questions