Regex to split camel case

前端 未结 12 1854
逝去的感伤
逝去的感伤 2020-11-28 23:31

I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here):



        
12条回答
  •  心在旅途
    2020-11-28 23:54

    I found that none of the answers for this question really worked in all cases and also not at all for unicode strings, so here's one that does everything, including dash and underscore notation splitting.

    let samples = [
      "ThereIsWay_too  MuchCGIInFilms These-days",
      "UnicodeCanBeCAPITALISEDTooYouKnow",
      "CAPITALLetters at the StartOfAString_work_too",
      "As_they_DoAtTheEND",
      "BitteWerfenSie-dieFußballeInDenMüll",
      "IchHabeUberGesagtNichtÜber",
      "2BeOrNot2Be",
      "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
    ];
    
    samples.forEach(sample => console.log(sample.replace(/([^[\p{L}\d]+|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}[\p{Ll}\d])|(?<=[\p{L}\d])(?=\p{Lu}[\p{Ll}\d]))/gu, '-').toUpperCase()));

    If you don't want numbers treated as lower case letters, then:

    let samples = [
      "2beOrNot2Be",
      "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
    ];
    
    samples.forEach(sample => console.log(sample.replace(/([^\p{L}\d]+|(?<=\p{L})(?=\d)|(?<=\d)(?=\p{L})|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})|(?<=[\p{L}\d])(?=\p{Lu}\p{Ll}))/gu, '-').toUpperCase()));

提交回复
热议问题