How to split a string by uppercase and lowercase in JavaScript?

ぃ、小莉子 提交于 2021-01-26 20:36:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!