javascript Regex split UpperCase from lowerCase

白昼怎懂夜的黑 提交于 2019-12-08 06:09:39

问题


I got a string like:

var str = new Array( 
"Inverted HFFSfor Primary Wrap Or Secondary Multi Wrap",
"HFFSwith PDSPbackgroud Feederlense & Product Alignerigit",
"HFFSwith Cooler JKLHbetween Feeder & Product Aligner")

How to separate i.e.

1) HFFSfor to become HFFS for

2) HFFSwith to become HFFS with

3) PDSPbackgroud to become PDSP backgroud

4) JKLHbetween to become JKLH between

and so forth...

My first instinc was something like:

for(var i = 0; i<_str.length; i++){ 
if( (/*The needed Regex*/).test(_str[i]) ){


     }  
}

No Success.... Can't seem to think further!!

Please help, Thanks


回答1:


indexOf doesn't accept a rgex, you can use a .replace like this.

You can use:

var repl = str.replace(/\B([a-z](?=[A-Z])|[A-Z](?=[a-z]))/g, '$1 ');

RegEx Demo

RegEx Breakup:

  • \B: Asserts positions where word boundary doesn't
  • (: Start capturing group #1
    • [a-z](?=[A-Z]): Match lowercase letter if there is a uppercase letter ahead
    • |: OR
    • [A-Z](?=[a-z]): Match uppercase letter if there is a lowercase letter ahead
  • ): End closing group #1



回答2:


You might try this, capture words that are made of more than one upper case letters (as one group) and lower case letters (as another group) and then add a space between the two groups:

var str = new Array( 
"Inverted HFFSfor Primary Wrap Or Secondary Multi Wrap",
"HFFSwith PDSPbackgroud Feederlense & Product Alignerigit",
"HFFSwith Cooler JKLHbetween Feeder & Product Aligner")

console.log(
  str.map(s => s.replace(/([A-Z]{2,})([a-z]+)/g, "$1 $2"))
)


来源:https://stackoverflow.com/questions/45282583/javascript-regex-split-uppercase-from-lowercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!