The split() method is the most appropriate way to split a string on capital letters.
Suppose you have a string like this "PizzaBurgerSandwich" and you wish to split it into the following:
"Pizza", "Burger", and "Sandwich".
If you call the split() method and pass a regular expression, i.e., [A-Z]
, it will split the string by capital letters.
let fastFood = "PizzaBurgerSandwich"; const result = fastFood.split(/[A-Z]/); console.log(result); //["", "izza", "urger", "andwich"]
You can see that the split() method has removed the capital letters.
Now, if you use character grouping to keep capital letters, then you will get the following array of substrings:
let fastFood = "PizzaBurgerSandwich"; const result = fastFood.split(/([A-Z])/); console.log(result); //["", "P", "izza", "B", "urger", "S", "andwich"]
You can see that the character grouping does not produce the required result.
When you pass a regular expression that uses a positive lookahead assertion, it will split a string on capital letters and return substrings in the form of an array.
let fastFood = "PizzaBurgerSandwich"; const result = fastFood.split(/(?=[A-Z])/); console.log(result); //["Pizza", "Burger", "Sandwich"]