Javascript Split string on UpperCase Characters

Javascript

Javascript Problem Overview


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']

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 3 - Javascript

Here you are :)

var arr = UpperCaseArray("ThisIsTheStringToSplit");

function UpperCaseArray(input) {
    var result = input.replace(/([A-Z]+)/g, ",$1").replace(/^,/, "");
    return result.split(",");
}

Solution 4 - Javascript

This is my solution which is fast, cross-platform, not encoding dependent, and can be written in any language easily without dependencies.

var s1 = "ThisЭтотΨόυτÜimunəՕրինակPříkladדוגמאΠαράδειγμαÉlda";
s2 = s1.toLowerCase();
result="";
for(i=0; i<s1.length; i++)
{
 if(s1[i]!==s2[i]) result = result +' ' +s1[i];
 else result = result + s2[i];
}
result.split(' ');

Solution 5 - Javascript

Here's an answer that handles numbers, fully lowercase parts, and multiple uppercase letters after eachother as well:

const wordRegex = /[A-Z]?[a-z]+|[0-9]+|[A-Z]+(?![a-z])/g;
const string = 'thisIsTHEString1234toSplit';
const result = string.match(wordRegex);

console.log(result)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicholas MurrayView Question on Stackoverflow
Solution 1 - JavascriptTeneffView Answer on Stackoverflow
Solution 2 - JavascriptMaxView Answer on Stackoverflow
Solution 3 - JavascriptManuel van RijnView Answer on Stackoverflow
Solution 4 - Javascriptuser10548418View Answer on Stackoverflow
Solution 5 - JavascriptMarcusView Answer on Stackoverflow