Javascript Split string on UpperCase Characters

How do you split a string into an array in JavaScript by Uppercase character?

So I wish to split:

'ThisIsTheStringToSplit'

into

['This', 'Is', 'The', 'String', 'To', 'Split']

Solution 1:

I would do this with .match() like this:

'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+/g);

it will make an array like this:

['This', 'Is', 'The', 'String', 'To', 'Split']

edit: since the string.split() method also supports regex it can be achieved like this

'ThisIsTheStringToSplit'.split(/(?=[A-Z])/); // positive lookahead to keep the capital letters

that will also solve the problem from the comment:

"thisIsATrickyOne".split(/(?=[A-Z])/);

Solution 2:

.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")

This should handle the numbers as well.. the join at the end results in concatenating all the array items to a sentence if that's what you looking for

'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")

Output

"This Is The String To Split"