Take the 2-minute tour ×

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!!

share|improve this question
add comment

2 Answers

up vote 7 down vote accepted

[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.

share|improve this answer
Perfect!! This works great!! Might I ask as a follow on, how, if possible, can I include 4 digit numbers like words to the result. For example 2011NowIsAGoodTime -> ['2011','Now','Is','A','Good','Time']. I can easily do this without regex (but of course Regex is more elegant :-) ) Thanks again for the solution to the original question; I understand it and it works perfectly. BTW, for me case, the optional 4 digit number, if present, will always be at the beginning of the string. –  user815460 Nov 11 '11 at 13:37
Your welcome, and thanks to @Marcus, too. /([0-9]{4}|[A-Z][a-z]*)/g should include 4-digit numbers. –  katspaugh Nov 11 '11 at 13:41
Thanks again for the help. Wow. This is great. Let me try to explain how it works for myself and others who might need an explanation. Please correct me if I'm wrong: Optionally match 4 digits or words that begin with A-Z followed by any number of a-z; the * only pertains to the [a-z]. Enclosing the whole expression in () is what causes the array to be returned, and the g at the end makes it work, but I'm not sure why. –  user815460 Nov 11 '11 at 13:50
Got it :-) Many thanks again!! –  user815460 Nov 11 '11 at 14:08
Parens were actually redundant! I've updated the answer. Thanks! –  katspaugh Nov 11 '11 at 14:12
add comment

This regex will break it up in desired parts:

share|improve this answer
add comment

Your Answer


