Split camelCase string with regex

I have a case Camel string like this s = 'ThisIsASampleString', and I want to split into an array using uppercase letters as a delimiter. I expect this:

['This', 'Is', 'A', 'Sample', 'String']

Here is what I have done so far

s = "ThisIsASampleString";
var regex = new RegExp('[A-Z]',"g");
var arr = s.split(re);

But this does not give me the correct result, because it removes the matching character. I get this array as a result ["his", "s", "", "tring"]. He removed all matching capital letters.

How to avoid this behavior and keep matching characters in my result array?

+4
source share
1 answer

, . , .

s = "ThisIsASampleString";
var arr = s.split(/(?=[A-Z])/);

console.log(arr);

Regex


String#match.

s = "ThisIsASampleString";
var arr = s.match(/[A-Z][^A-Z]*/g);

console.log(arr);

Regex

+6

Source: https://habr.com/ru/post/1664032/


All Articles