q.leroux
q.leroux

Reputation: 33

String: split / match Uppercase, space, specialchar

I know that they are already a lot of question about the subject but no answer for this one
I've tried for a while to split:

var string = "ABC hereWeAre Againwith Those words";

to

['A','B','C','here','We','Are','Againwith','Those','words'];

(When there is a UpperCase or a Space).

I've tried with :

string.match(/[A-Z]+|[a-z]+|[0-9]+|[\S]+/g);
string.match(/[a-z]+/gi);

But nothing is working.
Thanks for your help.

Upvotes: 2

Views: 594

Answers (2)

asleepysamurai
asleepysamurai

Reputation: 1372

The correct regex for this would be:

"ABC hereWeAre Againwith Those words".match(/[A-Z][a-z]*|[a-z]+/g);

Upvotes: 3

WTK
WTK

Reputation: 16971

Here it goes (a bit complicated but still works):

"ABC hereWeAre Againwith Those words".replace(/([A-Z])/g, ' $1').trim().split(/\s+/);
// returns ["A", "B", "C", "here", "We", "Are", "Againwith", "Those", "words"]

Idea is to find uppercase letters, prepend those with space, then trim and split whole string by spaces. Note passing regular expression into .split to get rid of problem with more than one space one after another.

Upvotes: 1

Related Questions