How to convert “camelCase” to “Camel Case”?

后端 未结 11 815
北荒
北荒 2020-11-27 10:25

I’ve been trying to get a JavaScript regex command to turn something like \"thisString\" into \"This String\" but the closest I’ve gotten is replac

相关标签:
11条回答
  • 2020-11-27 11:06
    "thisStringIsGood"
        // insert a space before all caps
        .replace(/([A-Z])/g, ' $1')
        // uppercase the first character
        .replace(/^./, function(str){ return str.toUpperCase(); })
    

    displays

    This String Is Good
    

    (function() {
    
      const textbox = document.querySelector('#textbox')
      const result = document.querySelector('#result')
      function split() {
          result.innerText = textbox.value
            // insert a space before all caps
            .replace(/([A-Z])/g, ' $1')
            // uppercase the first character
            .replace(/^./, (str) => str.toUpperCase())
        };
    
      textbox.addEventListener('input', split);
      split();
    }());
    #result {
      margin-top: 1em;
      padding: .5em;
      background: #eee;
      white-space: pre;
    }
    <div>
      Text to split
      <input id="textbox" value="thisStringIsGood" />
    </div>
    
    <div id="result"></div>

    0 讨论(0)
  • 2020-11-27 11:09

    This can be concisely done with regex lookahead (live demo):

    function splitCamelCaseToString(s) {
        return s.split(/(?=[A-Z])/).join(' ');
    }
    

    (I thought that the g (global) flag was necessary, but oddly enough, it isn't in this particular case.)

    Using lookahead with split ensures that the matched capital letter is not consumed and avoids dealing with a leading space if UpperCamelCase is something you need to deal with. To capitalize the first letter of each, you can use:

    function splitCamelCaseToString(s) {
        return s.split(/(?=[A-Z])/).map(function(p) {
            return p.charAt(0).toUpperCase() + p.slice(1);
        }).join(' ');
    }
    

    The map array method is an ES5 feature, but you can still use it in older browsers with some code from MDC. Alternatively, you can iterate over the array elements using a for loop.

    0 讨论(0)
  • 2020-11-27 11:09
    function spacecamel(s){
        return s.replace(/([a-z])([A-Z])/g, '$1 $2');
    }
    

    spacecamel('somethingLikeThis')

    // returned value: something Like This

    0 讨论(0)
  • 2020-11-27 11:13

    I think this should be able to handle consecutive uppercase characters as well as simple camelCase.

    For example: someVariable => someVariable, but ABCCode != A B C Code.

    The below regex works on your example but also the common example of representing abbreviations in camcelCase.

    "somethingLikeThis"
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z])([a-z])/g, ' $1$2')
        .replace(/\ +/g, ' ') => "something Like This"
    
    "someVariableWithABCCode"
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z])([a-z])/g, ' $1$2')
        .replace(/\ +/g, ' ') => "some Variable With ABC Code"
    

    You could also adjust as above to capitalize the first character.

    0 讨论(0)
  • 2020-11-27 11:17

    If you don't care about older browsers (or don't mind using a fallback reduce function for them), this can split even strings like 'xmlHTTPRequest' (but certainly the likes of 'XMLHTTPRequest' cannot).

    function splitCamelCase(str) {
            return str.split(/(?=[A-Z])/)
                      .reduce(function(p, c, i) {
                        if (c.length === 1) {
                            if (i === 0) {
                                p.push(c);
                            } else {
                                var last = p.pop(), ending = last.slice(-1);
                                if (ending === ending.toLowerCase()) {
                                    p.push(last);
                                    p.push(c);
                                } else {
                                    p.push(last + c);
                                }
                            }
                        } else {
                            p.push(c.charAt(0).toUpperCase() + c.slice(1));
                        }
                        return p;
                      }, [])
                      .join(' ');
    }
    
    0 讨论(0)
提交回复
热议问题