145

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']
skmak
  • 357
  • 3
  • 12
Nicholas Murray
  • 12,971
  • 14
  • 63
  • 82
  • This could end up being useful for some people looking for a solution to this problem: http://stackoverflow.com/a/25732260/1454888 – Augusto Barreto Mar 11 '16 at 23:14

5 Answers5

301

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])/);
Teneff
  • 26,872
  • 8
  • 62
  • 92
  • 61
    This will not find single uppercase characters. I suggest the following: `"thisIsATrickyOne".match(/([A-Z]?[^A-Z]*)/g).slice(0,-1)` – andrewmu Oct 25 '11 at 11:25
  • 3
    Back into a readable string `"thisIsATrickyOne".match(/([A-Z]?[^A-Z]*)/g).slice(0,-1).join(" ")` gives `this Is A Tricky One` – Simon Hutchison Jun 02 '21 at 00:14
34
.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"
Max
  • 509
  • 5
  • 6
  • 1
    This is perfect. But anyone using this should be careful in the following case: `'ThisIs8TheSt3ringToSplit'.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")` will output `This Is 8 The St 3 To Split`, ommitting the small case string(`ring`) after `3`. – Diablo Jul 19 '19 at 09:32
10

Here you are :)

var arr = UpperCaseArray("ThisIsTheStringToSplit");

function UpperCaseArray(input) {
    var result = input.replace(/([A-Z]+)/g, ",$1").replace(/^,/, "");
    return result.split(",");
}
Manuel van Rijn
  • 9,957
  • 1
  • 26
  • 50
8

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(' ');
3

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)
Marcus
  • 171
  • 2
  • 9