Search code examples
javascript

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

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

    // positive lookahead to keep the capital letters
    r = 'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+/g);
    
    console.log(r)

    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

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

    that will also solve the problem from the comment:

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

    Update: to split on Uppercase character, not preceded with another Uppercase character, a negative lookbehind can be used

    r = 'SplitOrderID'.split(/(?<![A-Z])(?=[A-Z])/);
    
    console.log(r)