6

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?

Ezio
  • 2,837
  • 2
  • 29
  • 45

1 Answers1

8

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(/(?=[A-Z])/);

console.log(arr);

Regex explanation here


Or you can use String#match method instead.

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

console.log(arr);

Regex explanation here

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Although I have a question, why is it happening, why those capital letters were getting removed upon matching? – Ezio Dec 17 '16 at 07:28
  • 1
    @Ezio : the string is getting split based on the matched separator.... check the MDN docs it may help you : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split – Pranav C Balan Dec 17 '16 at 07:30