简体   繁体   中英

Split a camelCase string with regex

I have a Camel case string like this s = 'ThisIsASampleString' and I want to split into an array using the capital letters as the delimiting point. I am expecting 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 is not giving me the correct result because it removes the matched character. I am getting this array as my result ["his", "s", "", "tring"] . It has removed all the matched capital letters.

How should I avoid this behavior and keep the matched characters also in my result array?

Your regex would split based on the uppercase but the result array doesn't include the matched value. Instead use positive look-ahead assertion to assert the position.

 s = "ThisIsASampleString"; var arr = s.split(/(?=[AZ])/); console.log(arr); 

Regex explanation here


Or you can use String#match method instead.

 s = "ThisIsASampleString"; var arr = s.match(/[AZ][^AZ]*/g); console.log(arr); 

Regex explanation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM