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);
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);
Share
Improve this question
asked May 10, 2016 at 0:21
HaloorHaloor
2214 silver badges14 bronze badges
5
|
3 Answers
Reset to default 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
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('!!');
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('!');
};
/(?:[A-Z]+|[^A-Z]+)/g
regex101.com/r/hR3kE3/1 – user1106925 Commented May 10, 2016 at 0:36