Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 831
Haloor Avatar asked May 10 '16 00:05

Haloor


People also ask

How do you use lowercase and uppercase in JavaScript?

JavaScript provides two helpful functions for converting text to uppercase and lowercase. String. toLowerCase() converts a string to lowercase, and String. toUpperCase() converts a string to uppercase.

How do you separate lowercase and uppercase in Java?

Answer: There are isUpperCase() and isLowerCase() methods available in String class to check the upper case and lower case characters respectively.

Is there a capitalize method in JavaScript?

In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase.

Is JavaScript split case sensitive?

The split() method splits the string into an array of substrings based on a specified value (case-sensitive) and returns the array.


2 Answers

([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

like image 168
yelsayed Avatar answered Sep 21 '22 15:09

yelsayed


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('!!');
like image 24
omarjmh Avatar answered Sep 21 '22 15:09

omarjmh