问题
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);
回答1:
([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
回答2:
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('!!');
回答3:
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('!');
};
来源:https://stackoverflow.com/questions/37127422/how-to-split-a-string-by-uppercase-and-lowercase-in-javascript