Dan
Dan

Reputation: 57881

Split string using multi-character delimiters

I want to split a text using delimiters that can be longer than one symbol.

For example, this should be split using and, or and comma:

"red lorry, yellow lorry and brown lorry".split(someRegexp)

should produce:

["red lorry", " yellow lorry", "brown lorry"]

It's not necessary for regex to trim spaces, this can be done later.

Upvotes: 0

Views: 150

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can use the regex

/,|\b\s*(?:and|or)\s*\b/

Example

> "red lorry, yellow lorry and brown lorry".split(/,|\b\s*(?:and|or)\s*\b/)
< ["red lorry", " yellow lorry", "brown lorry"]
  • \b Matches word boundaries. This ensure that the or and and are not matched within another word.

Upvotes: 3

Related Questions