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);
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.
Answer: There are isUpperCase() and isLowerCase() methods available in String class to check the upper case and lower case characters respectively.
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.
The split() method splits the string into an array of substrings based on a specified value (case-sensitive) and returns the array.
([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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With