Regex to split camel case

前端 未结 12 1807
逝去的感伤
逝去的感伤 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:56

    If you want an array of lower case words:

    "myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase());
    

    If you want a string of lower case words:

    "myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase()).join(' ');
    

    If you want to separate the words but keep the casing:

    "myCamelCaseString".replace(/([a-z])([A-Z])/g, '$1 $2')
    
    0 讨论(0)
  • 2020-11-28 23:59

    Hi I saw no live demo , thanks @michiel-dral

    var tests =[ "camelCase",
                 "simple",
                 "number1Case2"]
    
    function getCamelCaseArray(camel) {
      var reg = /([a-z0-9])([A-Z])/g;
      return camel.replace(reg, '$1 $2').split(' ');
    }
    
    function printTest(test) {
    document.write('<p>'+test + '=' + getCamelCaseArray(test)+'</p>');
    }
    
    tests.forEach(printTest);
    <!DOCTYPE html>
    <html>
    
      <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"></script>
      </head>
    
      <body>
      </body>
    
    </html>

    0 讨论(0)
  • 2020-11-29 00:00

    Sometime camelCase strings include abbreviations, for example:

    PDFSplitAndMergeSamples
    PDFExtractorSDKSamples
    PDFRendererSDKSamples
    BarcodeReaderSDKSamples
    

    And in this case the following function will work, it splits the string leaving abbreviations as separate strings:

    function SplitCamelCaseWithAbbreviations(s){
       return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
    }
    

    Example:

    function SplitCamelCaseWithAbbreviations(s){
       return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
    }
    
    console.log(SplitCamelCaseWithAbbreviations('PDFSplitAndMergeSamples'));
    console.log(SplitCamelCaseWithAbbreviations('PDFExtractorSDKSamples'));
    console.log(SplitCamelCaseWithAbbreviations('PDFRendererSDKSamples'));
    console.log(SplitCamelCaseWithAbbreviations('BarcodeReaderSDKSamples'));

    0 讨论(0)
  • 2020-11-29 00:00
    a = 'threeBlindMice'
    a.match(/[A-Z]?[a-z]+/g) // [ 'three', 'Blind', 'Mice' ]
    

    is the simplest way I've found, for simple camel/titlecase splitting.

    0 讨论(0)
  • 2020-11-29 00:01

    This RegExp String is

    .replace("/([a-zA-Z][a-z]*)/g",...);
    
    0 讨论(0)
  • 2020-11-29 00:04
    "MyCamelCaseString".replace(/([a-z](?=[A-Z]))/g, '$1 ')
    

    outputs:

    "My Camel Case String"
    
    0 讨论(0)
提交回复
热议问题