Reputation: 1
I'd like to split a string if:
quatre
or a soixante
ANDdix
or a vingt
For example:
'deux-cent-quatre-vingt-trois'.split(/**/);
> ['deux', 'cent', 'quatre-vingt', 'trois' ]
I've had a few tries and failures, for example:
'deux-cent-quatre-vingt-dix-trois'
.split(/^(?![quatre|soixante]-[dix|vingt])(\w*)-(\w*)/);
> [ '', 'deux', 'cent', '-quatre-vingt-trois' ]
or:
'deux-cent-quatre-vingt-dix-trois'.split(/(?!quatre|soixante)-(?!vingt|dix)/);
> [ 'deux' 'cent', 'quatre-vingt', 'trois' ]
which works, but this does not:
'cent-vingt'.split(/(?!quatre|soixante)-(?!vingt|dix)/);
> [ 'cent-vingt' ]
I know using a matcher or a find would be so easy, but it would be great to do it in a single split...
Upvotes: 0
Views: 581
Reputation: 89557
You can do it like this:
var text = "deux-cent-quatre-vingt-trois";
console.log(text.split(/(?:^|-)(quatre-vingt(?:-dix|s$)?|soixante-dix|[^-]+)/));
The idea is to add a capturing group whose content is added to the split list.
The capturing group contains at first particular cases and after the most general, described with [^-]+
(all that is not a -
)
Notice: since quatre-vingt
is written with a s
when it is not followed by a number, i added s$
as a possibility.
Upvotes: 1