最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - How to split a string by uppercase and lowercase in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

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
  • Seems to be a duplicate of stackoverflow.com/a/7599674/586030 – Aaron Cicali Commented May 10, 2016 at 0:31
  • 2 Give this a try: /(?:[A-Z]+|[^A-Z]+)/g regex101.com/r/hR3kE3/1 – user1106925 Commented May 10, 2016 at 0:36
  • that worked perfectly, squint - however, I can't set Q as answered as you posted a comment – Haloor Commented May 10, 2016 at 0:43
  • Glad it helped. You've got other answers below you can mark. – user1106925 Commented May 10, 2016 at 0:44
  • duplicate Javascript Split string on UpperCase Characters – Baby Commented May 11, 2016 at 0:44
Add a comment  | 

3 Answers 3

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('!');
};
发布评论

评论列表(0)

  1. 暂无评论