5

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

2 Answers 2

12
'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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Your welcome, and thanks to @Marcus, too. /([0-9]{4}|[A-Z][a-z]*)/g should include 4-digit numbers.
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.
Parens were actually redundant! I've updated the answer. Thanks!
2

This regex will break it up in desired parts:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.