Split by Caps in Javascript

前端 未结 4 1474
说谎
说谎 2020-12-01 11:57

I am trying to split up a string by caps using Javascript,

Examples of what Im trying to do:

\"HiMyNameIsBob\"  ->   \"Hi My Name Is Bob\"
\"Greet         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 12:18

    You can use String.match to split it.

    "HiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g) 
    // output 
    // ["Hi", "My", "Name", "Is", "Bob"]
    

    If you have lowercase letters at the beginning it can split that too. If you dont want this behavior just use + instead of * in the pattern.

    "helloHiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g) 
    // Output
    ["hello", "Hi", "My", "Name", "Is", "Bob"]
    

提交回复
热议问题