Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string based of capital letters?

I have a string I need to split based on capital letters,my code below

let s = 'OzievRQ7O37SB5qG3eLB';
var res = s.split(/(?=[A-Z])/)
console.log(res);

But there is a twist,if the capital letters are contiguous I need the regex to "eat" until this sequence ends.In the example above it returns

..R,Q7,O37,S,B5q,G3e,L,B

And the result should be

RQ7,O37,SB5q,G3e,LB

Thoughts?Thanks.

like image 536
Mihai Avatar asked Dec 13 '25 13:12

Mihai


1 Answers

You need to match these chunks with /[A-Z]+[^A-Z]*|[^A-Z]+/g instead of splitting with a zero-width assertion pattern, because the latter (in your case, it is a positive lookahead only regex) will have to check each position inside the string and it is impossible to tell the regex to skip a position once the lookaround pattern is found.

s = 'and some text hereOzievRQ7O37SB5qG3eLB';
console.log(s.match(/[A-Z]+[^A-Z]*|[^A-Z]+/g));

See the online regex demo at regex101.com.

Details:

  • [A-Z]+ - one or more uppercase ASCII letters
  • [^A-Z]* - zero or more (to allow matching uppercase only chunks) chars other than uppercase ASCII letters
  • | - or
  • [^A-Z]+ - one or more chars other than uppercase ASCII letters (to allow matching non-uppercase ASCII letters at the start of the string.

The g global modifier will let String#match() return all found non-overlapping matches.

like image 166
Wiktor Stribiżew Avatar answered Dec 15 '25 03:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!