Home > database >  How do I split a string only when capitalized letters are sticking to another word
How do I split a string only when capitalized letters are sticking to another word

Time:05-22

how do I split a string ONLY if capitalized letters are next to a word without spaces. so, only if 'aBa' but not if 'A B'

I want to split:

'John DoeJane DoeOther Doe'

into

['John Doe', 'Jane Doe', 'Other Doe']

I already know how to split just by capitalized letters, like on this issue right here. But I don't want to split for every capitalized letter and separate 'John' from 'Doe' or any of the others.

CodePudding user response:

Try this

const re = /[A-Z][a-z] \s[A-Z][a-z] /g;
const str = 'John DoeJane DoeOther Doe';
console.log(str.match(re));

Reference: Regular expressions

CodePudding user response:

You can split on matches of the regular expression

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

Demo

(?<=[a-z]) is a positive lookbehind that requires the previous character to be a lowercase letter; (?=[A-Z]) is a positive lookahead that requires the following character to be an uppercase letter. For the string

'John DoeJane DoeOther Doe'

this matches the zero-width locations between 'e' and 'J' and between between 'e' and 'O'.

  • Related