Split a String on Capital Letters using JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

Split a String on Capital Letters in JavaScript #

To split a string on capital letters, call the split() method with the following regular expression - /(?=[A-Z])/. The regular expression uses a positive lookahead assertion to split the string on each capital letter and return an array of the substrings.

index.js
const str = 'OneTwoThree'; const result = str.split(/(?=[A-Z])/); // ๐Ÿ‘‡๏ธ ['One', 'Two', 'Three'] console.log(result);

The only parameter we passed to the String.split method is a regular expression.

The forward slashes / / mark the beginning and end of the regular expression.

Our regular expression uses a positive lookahead assertion. Lookahead assertions don't consume a character, which allows us to keep the capital letters in the results.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.

If your string contains spaces, the substrings in the array will contain trailing spaces.

index.js
const str = 'One Two Three'; const result = str.split(/(?=[A-Z])/); // ๐Ÿ‘‡๏ธ ['One ', 'Two ', 'Three'] console.log(result);

Similarly, if the string starts with a space, you will get an array element that contains an empty space.

index.js
const str = ' One Two Three '; const result = str.split(/(?=[A-Z])/); // ๐Ÿ‘‡๏ธ [' ', 'One , 'Two ', 'Three '] console.log(result);

To handle these edge cases we can use the String.trim and Array.map methods.

index.js
const str = ' One Two Three '; const result = str .trim() .split(/(?=[A-Z])/) .map(element => element.trim()); // ๐Ÿ‘‡๏ธ ['One , 'Two', 'Three'] console.log(result);

We used the trim() method to remove any leading or trailing spaces from the original string.

index.js
// ๐Ÿ‘‡๏ธ "abc" console.log(' abc '.trim());

Then we called the split() method to split the string on each capital letter.

Lastly, we used the map() method to remove any leading or trailing spaces from the strings in the array.

The function we passed to the map method gets called with each element in the array.

On each iteration, we trim the string to remove the surrounding spaces and return the result.

The map method returns a new array that consists of the values the callback function returned.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee