user815460
user815460

Reputation: 1143

Use Regex in Javascript to return an array of words

Try though I may, can't figure out how to use regex in javascript to get an array of words (assuming all words are capitalized). For example:

Given this: NowIsAGoodTime

How can you use regex to get: ['Now','Is','A','Good','Time']

Thanks Very Much!!

Upvotes: 5

Views: 10784

Answers (2)

katspaugh
katspaugh

Reputation: 17899

'NowIsAGoodTime'.match(/[A-Z][a-z]*/g)

[A-Z], [a-z] and [0-9] are character sets defined as ranges. They could be [b-xï], for instance (from "b" to "x" plus "ï").

String.prototype.match always returns an array or null if no match at all.

Finally, the g regexp flag stands for "global match". It means, it will try to match the same pattern on subsequent string parts. By default (with no g flag), it will be satisfied with the first match.

With a globally matching regexp, match returns an array of matching substrings.

With single match regexps, it would return the substring matched to the whole pattern, followed by the pattern groups matches. E. g.:

'Hello'.match(/el(lo)/) // [ 'ello', 'lo' ]

See more on Regexp.

Upvotes: 12

Marcus
Marcus

Reputation: 12586

This regex will break it up in desired parts:

([A-Z][a-z]*)

Upvotes: 2

Related Questions