javascript - How to split a string based of capital letters? - Stack Overflow

I have a string I need to split based on capital letters,my code belowlet s = 'OzievRQ7O37SB5qG3eL

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);

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.

Share Improve this question asked Mar 15, 2017 at 8:50 MihaiMihai 26.8k8 gold badges69 silver badges86 bronze badges 3
  • 1 'OzievRQ7O37SB5qG3eLB'.match(/[A-Z]+[^A-Z]+/g) ? – Andrey Commented Mar 15, 2017 at 8:57
  • @Andrey Post it as an answer – Mihai Commented Mar 15, 2017 at 9:00
  • Wiktor got it :) His regex is actually better – Andrey Commented Mar 15, 2017 at 9:03
Add a ment  | 

1 Answer 1

Reset to default 5

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..

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745037221a4607594.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信