javascript Regex split UpperCase from lowerCase

2019-06-01 08:45发布

问题:

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