javascriptregexstringecmascript-2018

Split JS string regex upper followed by lowercase


I have a long javascript variable articles that I am trying to split where a lowercase character is immediately followed by an uppercase

Using regex I have tried:

var article2 = article2.split(/(?=[A-Z][a-z])/); 

but only managed to split on every word


Solution

  • Since your JS environment is ECMAScript 2018 compliant (see what regex features it supports), you may use lookbehinds:

    .split(/(?<=[a-z])(?=[A-Z])/)
    

    A (?<=[a-z]) pattern is a lookbehind that requires a digit immediately to the left of the current location and (?=[A-Z]) is a positive lookahead that requires a digit immediately to the right of the current location.

    See the regex demo.