Convert camelCaseText to Sentence Case Text

后端 未结 20 2051
闹比i
闹比i 2020-11-28 03:44

How can I convert a string either like \'helloThere\' or \'HelloThere\' to \'Hello There\' in JavaScript?

相关标签:
20条回答
  • 2020-11-28 04:37

    Example without side effects.

    function camel2title(camelCase) {
      // no side-effects
      return camelCase
        // inject space before the upper case letters
        .replace(/([A-Z])/g, function(match) {
           return " " + match;
        })
        // replace first char with upper case
        .replace(/^./, function(match) {
          return match.toUpperCase();
        });
    }
    

    In ES6

    const camel2title = (camelCase) => camelCase
      .replace(/([A-Z])/g, (match) => ` ${match}`)
      .replace(/^./, (match) => match.toUpperCase());
    
    0 讨论(0)
  • 2020-11-28 04:37

    Input javaScript

    Output Java Script

       var text = 'javaScript';
        text.replace(/([a-z])([A-Z][a-z])/g, "$1 $2").charAt(0).toUpperCase()+text.slice(1).replace(/([a-z])([A-Z][a-z])/g, "$1 $2");
    
    0 讨论(0)
提交回复
热议问题