1

i'm trying to split a String which contains an Uppercase Part + a Lowercase Part in Javascript (ES5). The String always looks like "UPPERlower".

Here's what i currently use

"ABCabc".match(/^[A-Z]+/g).concat("ABCabc".match(/[a-z]+$/g)) //result is ["ABC", "abc"]

Is there a cleaner code to achieve this?

EDIT: Ori Drori's answer and mplungjan's answer are both correct for my Problem.

Frozzo
  • 15
  • 4

2 Answers2

0

You can use | to match either the uppercase or lowercase sequence:

var result = "ABCabc".match(/[A-Z]+|[a-z]+/g)

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Destructuring is the modern way

const s="UPPERlower";
let [,upper, lower] =/([A-Z]+)([a-z]+)/g.exec(s);
console.log(upper,lower);

Looping - NOTE: What is the difference between RegExp’s exec() function and String’s match() function?

const s = "UPPERlower UPlow 123 lowUP UPPlowe"; 
// Note:above will produce low UP using .match(/[A-Z]+|[a-z]+/g) instead of capturing
const re = /([A-Z]+)([a-z]+)/g;
while (match = re.exec(s)) {
  [, upper, lower] = match;
  console.log(upper, lower)
}

Older way:

var parts=/([A-Z]+)([a-z]+)/g.exec("UPPERlower");
console.log(parts[1],parts[2]);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Thanks this works, although i dont really understand what you achieve by using let [, upper, lower]? Are you creating an array like [null, value of first part of regex, value of second part of regex]? – Frozzo Jan 29 '18 at 12:05
  • I create vars and ignore the first element of the exec: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – mplungjan Jan 29 '18 at 12:08
  • Wow, i did not know that was a thing, gotta thank you for that :). But I give the correct answer to Ori Drori for being pure ES5 (i know const and let are easily replaced), for ES6 this definitvly seems like the right answer, so i added a comment to my question linking to this as ES6 answer – Frozzo Jan 29 '18 at 12:12
  • I added an example using more backwards compatible JS - my exec is not very different from .match – mplungjan Jan 29 '18 at 12:13
  • Hmm, so if i have a simple regex match is fine, but if i had a complex regex exec would be better? Or is there a real advantage you get with 1 over the other? – Frozzo Jan 29 '18 at 12:16
  • https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun# – mplungjan Jan 29 '18 at 12:22
  • Thanks a lot, this really helped me understand more, of whats going on in the background :D. – Frozzo Jan 29 '18 at 12:28
  • I added a loop. Also read this: https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun – mplungjan Jan 29 '18 at 12:45