Split a String on Capital Letters using JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

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 returns 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.

The 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, check out this regex cheatsheet from MDN.

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 a space.

index.js
const str = ' One Two Three '; const result = str.split(/(?=[A-Z])/); // 👇️ [' ', 'One , 'Two ', 'Three '] console.log(result);

We can use the String.trim and Array.map methods to handle these edge cases.

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 and trailing spaces from the original string.

index.js
// 👇️ "abc" console.log(' abc '.trim());

We then 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 leading and trailing spaces and return the result.

The map method returns a new array that contains the values we returned from the callback function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.