12

Is it possible to split Strings in JavaScript by case such that the following string below (myString) would be converted into the array (myArray) below:

var myString = "HOWtoDOthis";
var myArray = ["HOW", "to", "DO", "this"];

I have tried the regex below, but it only splits for camelCase:

.match(/[A-Z]*[^A-Z]+/g);
Haloor
  • 221
  • 4
  • 14
  • Seems to be a duplicate of http://stackoverflow.com/a/7599674/586030 – Aaron Cicali May 10 '16 at 00:31
  • 2
    Give this a try: `/(?:[A-Z]+|[^A-Z]+)/g` https://regex101.com/r/hR3kE3/1 –  May 10 '16 at 00:36
  • that worked perfectly, squint - however, I can't set Q as answered as you posted a comment – Haloor May 10 '16 at 00:43
  • Glad it helped. You've got other answers below you can mark. –  May 10 '16 at 00:44
  • duplicate [Javascript Split string on UpperCase Characters](http://stackoverflow.com/questions/7888238/javascript-split-string-on-uppercase-characters) – Baby May 11 '16 at 00:44

3 Answers3

10

([A-Z]+|[a-z]+). Match all upper case, or all lower case multiple times in capturing groups. Give this a try here: https://regex101.com/r/bC8gO3/1

yelsayed
  • 5,236
  • 3
  • 27
  • 38
4

Another way to do this is to add in a marker and then split using that marker, in this case a double-exclamation point:

JsBin Example

var s = "HOWtoDOthis";

var t = s.replace(/((?:[A-Z]+)|([^A-Z]+))/g, '!!$&').split('!!');
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

If you want to split an CamelCased String following will work

/**
 * howToDoThis ===> ["", "how", "To", "Do", "This"]
 * @param word word to be split
 */
export const splitCamelCaseWords = (word: string) => {
    if (typeof word !== 'string') return [];
    return word.replace(/([A-Z]+|[A-Z]?[a-z]+)(?=[A-Z]|\b)/g, '!$&').split('!');
};
Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73