关于javascript:将camelCaseText转换为句子案例文本

Convert camelCaseText to Sentence Case Text

在javascript中,如何将类似"hello there"或"hellothere"的字符串转换为"hello there"?


1
2
3
var text = 'helloThereMister';
var result = text.replace( /([A-Z])/g," $1" );
var finalResult = result.charAt(0).toUpperCase() + result.slice(1); // capitalize the first letter - as an example.

注意EDOCX1[0]中的空格。

编辑:添加了第一个字母大写的示例。当然,如果第一个字母已经是大写的话,你就有多余的空间可以删除。


或者使用矿粉:

1
lodash.startCase(str);

例子:

1
2
_.startCase('helloThere');
// ? 'Hello There'

Lodash是一个很好的库,可以为许多日常的JS任务提供快捷方式,还有许多类似的字符串操作功能,如camelCasekebabCase等。


我也遇到过类似的问题,我是这样处理的:

1
stringValue.replace(/([A-Z]+)*([A-Z][a-z])/g,"$1 $2")

对于更强大的解决方案:

1
stringValue.replace(/([A-Z]+)/g," $1").replace(/([A-Z][a-z])/g," $1")

http://jsfiddle.net/peyyq/

输入:

1
2
3
4
 helloThere
 HelloThere
 ILoveTheUSA
 iLoveTheUSA

输出:

1
2
3
4
 hello There
 Hello There
 I Love The USA
 i Love The USA

没有副作用的例子。

1
2
3
4
5
6
7
8
9
10
11
12
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();
    });
}

在ES6中

1
2
3
const camel2title = (camelCase) => camelCase
  .replace(/([A-Z])/g, (match) => ` ${match}`)
  .replace(/^./, (match) => match.toUpperCase());


我为测试camel case-to-title case函数找到的最好的字符串是这个荒谬的无意义的例子,它测试了许多边缘情况。据我所知,以前发布的函数中没有一个能正确处理这个问题:

将26abc作为资产专用个人卡用于456inoom26acontaingbc26times对于c3poorr2d2or2r2d来说不可能是123。

应将其转换为:

要想及时获得GED,一首关于26个ABC的歌是很重要的,但是在26A房间为456名用户准备的包含ABC 26次的个人身份证并不像C3PO、R2D2或2R2D那样简单。

如果您只需要一个简单的函数来处理像上面这样的情况(并且比以前的许多答案还要多),这里是我写的。这段代码不是特别优雅或快速,但它简单、易懂,并且可以工作。

它的在线可运行示例如下:http://jsfiddle.net/q5gbye2w/56/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries.
//
// E.g.:
//    ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
//                                                  --> To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D
//    helloThere                              --> Hello There
//    HelloThere                              --> Hello There
//    ILoveTheUSA                             --> I Love The USA
//    iLoveTheUSA                             --> I Love The USA
//    DBHostCountry                           --> DB Host Country
//    SetSlot123ToInput456                    --> Set Slot 123 To Input 456
//    ILoveTheUSANetworkInTheUSA              --> I Love The USA Network In The USA
//    Limit_IOC_Duration                      --> Limit IOC Duration
//    This_is_a_Test_of_Network123_in_12_days --> This Is A Test Of Network 123 In 12 Days
//    ASongAboutTheABCsIsFunToSing                  --> A Song About The ABCs Is Fun To Sing
//    CFDs                                    --> CFDs
//    DBSettings                              --> DB Settings
//    IWouldLove1Apple                        --> 1 Would Love 1 Apple
//    Employee22IsCool                        --> Employee 22 Is Cool
//    SubIDIn                                 --> Sub ID In
//    ConfigureCFDsImmediately                --> Configure CFDs Immediately
//    UseTakerLoginForOnBehalfOfSubIDInOrders --> Use Taker Login For On Behalf Of Sub ID In Orders
//
function camelCaseToTitleCase(in_camelCaseString) {
        var result = in_camelCaseString                         //"ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
            .replace(/([a-z])([A-Z][a-z])/g,"$1 $2")           //"To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times IsNot AsEasy As123ForC3POOrR2D2Or2R2D"
            .replace(/([A-Z][a-z])([A-Z])/g,"$1 $2")           //"To Get YourGEDIn TimeASong About The26ABCs Is Of The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
            .replace(/([a-z])([A-Z]+[a-z])/g,"$1 $2")          //"To Get Your GEDIn Time ASong About The26ABCs Is Of The Essence But APersonal IDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
            .replace(/([A-Z]+)([A-Z][a-z][a-z])/g,"$1 $2")     //"To Get Your GEDIn Time A Song About The26ABCs Is Of The Essence But A Personal ID Card For User456In Room26A ContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
            .replace(/([a-z]+)([A-Z0-9]+)/g,"$1 $2")           //"To Get Your GEDIn Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3POOr R2D2Or 2R2D"
           
            // Note: the next regex includes a special case to exclude plurals of acronyms, e.g."ABCs"
            .replace(/([A-Z]+)([A-Z][a-rt-z][a-z]*)/g,"$1 $2") //"To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"
            .replace(/([0-9])([A-Z][a-z]+)/g,"$1 $2")          //"To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC 26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"  

                        // Note: the next two regexes use {2,} instead of + to add space on phrases like Room26A and 26ABCs but not on phrases like R2D2 and C3PO"
            .replace(/([A-Z]{2,})([0-9]{2,})/g,"$1 $2")        //"To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
            .replace(/([0-9]{2,})([A-Z]{2,})/g,"$1 $2")        //"To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
            .trim();


  // capitalize the first letter
  return result.charAt(0).toUpperCase() + result.slice(1);
}

或者,正如用户巴诺建议的那样,如果您不介意加入这个库,那么使用SugarJS是一个简单的解决方案。但是,我不确定它是否处理我上面描述的测试字符串;我没有在那个输入上尝试过它。


这是我的版本。它在每一个大写英文字母前加上一个空格,在小写英文字母后加上第一个字母的大写字母(如果需要):

例如:这是camel case——>这是camel case这是camel case——>这是camel case这是camel case123——>这是camel case123

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  function camelCaseToTitleCase(camelCase){
    if (camelCase == null || camelCase =="") {
      return camelCase;
    }

    camelCase = camelCase.trim();
    var newText ="";
    for (var i = 0; i < camelCase.length; i++) {
      if (/[A-Z]/.test(camelCase[i])
          && i != 0
          && /[a-z]/.test(camelCase[i-1])) {
        newText +="";
      }
      if (i == 0 && /[a-z]/.test(camelCase[i]))
      {
        newText += camelCase[i].toUpperCase();
      } else {
        newText += camelCase[i];
      }
    }

    return newText;
  }


好吧,我迟到了几年,但我有一个类似的问题,我想为每一个可能的输入制定一个替代方案。我必须把大部分功劳都归功于@Zenmaster和@Benjamin Udink Ten Cate。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var camelEdges = /([A-Z](?=[A-Z][a-z])|[^A-Z](?=[A-Z])|[a-zA-Z](?=[^a-zA-Z]))/g;
var textArray = ["lowercase",
                "Class",
                "MyClass",
                "HTML",
                "PDFLoader",
                "AString",
                "SimpleXMLParser",
                "GL11Version",
                "99Bottles",
                "May5",
                "BFG9000"];
var text;
var resultArray = [];
for (var i = 0; i < a.length; i++){
    text = a[i];
    text = text.replace(camelEdges,'$1 ');
    text = text.charAt(0).toUpperCase() + text.slice(1);
    resultArray.push(text);
}

它有三个子句,都使用lookahead来防止regex引擎使用过多的字符:

  • [A-Z](?=[A-Z][a-z])查找一个大写字母,后跟一个大写字母,然后是一个小写字母。这是为了结束像美国这样的缩写词。
  • [^A-Z](?=[A-Z])查找一个非大写字母,后跟一个大写字母。这句话的结尾是"我的话",符号是"99瓶"。
  • [a-zA-Z](?=[^a-zA-Z])查找一个字母后跟一个非字母。这在诸如bfg9000这样的符号之前结束单词。
  • 这个问题在我的搜索结果中居首位,所以希望我能节省一些时间!


    您可以使用这样的函数:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    function fixStr(str) {
        var out = str.replace(/^\s*/,"");  // strip leading spaces
        out = out.replace(/^[a-z]|[^\s][A-Z]/g, function(str, offset) {
            if (offset == 0) {
                return(str.toUpperCase());
            } else {
                return(str.substr(0,1) +"" + str.substr(1).toUpperCase());
            }
        });
        return(out);
    }

    "hello World" ==>"Hello World"
    "HelloWorld" ==>"Hello World"
    "FunInTheSun" ==?"Fun In The Sun"

    这里有一组测试字符串的代码:http://jsfiddle.net/jfriend00/fwluv/。

    这里保留前导空格的替代版本:http://jsfiddle.net/jfriend00/uy2ac/。


    基于上面的一个例子,我得出了以下结论:

    1
    2
    3
    4
    const camelToTitle = (camelCase) => camelCase
      .replace(/([A-Z])/g, (match) => ` ${match}`)
      .replace(/^./, (match) => match.toUpperCase())
      .trim()

    它对我有用,因为它使用.trim()来处理第一个字母大写的边缘大小写,最后得到一个额外的前导空格。

    参考文献:https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/trim


    试试这个图书馆

    http://sugarjs.com/api/string/titleize

    1
    2
    3
    4
    'man from the boondocks'.titleize()>"Man from the Boondocks"
    'x-men: the last stand'.titleize()>"X Men: The Last Stand"
    'TheManWithoutAPast'.titleize()>"The Man Without a Past"
    'raiders_of_the_lost_ark'.titleize()>"Raiders of the Lost Ark"


    这对我有用,看看这个

    CamelcaseToWord("MyName"); // returns My Name

    1
    2
    3
        function CamelcaseToWord(string){
          return string.replace(/([A-Z]+)/g," $1").replace(/([A-Z][a-z])/g," $1");
        }


    我没有尝试每个人的答案,但我修补的几个解决方案不符合我的所有要求。

    我能想出一些……

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    export const jsObjToCSSString = (o={}) =>
        Object.keys(o)
              .map(key => ({ key, value: o[key] }))
              .map(({key, value}) =>
                  ({
                    key: key.replace( /([A-Z])/g,"-$1").toLowerCase(),
                    value
                  })
              )
              .reduce(
                  (css, {key, value}) =>
                      `${css} ${key}: ${value}; `.trim(),
                  '')


    下面是使用regex演示camel case字符串到句子字符串的链接。

    输入

    myCamelCaseSTRINGToSPLITDemo

    产量

    江户十一〔一〕号

    这是将camel大小写转换为句子文本的regex

    1
    (?=[A-Z][a-z])|([A-Z]+)([A-Z][a-rt-z][a-z]\*)

    $1 $2作为替代。

    单击此处可查看regex上的转换


    我认为这可以通过Reg exp /([a-z]|[A-Z]+)([A-Z])/g和替换"$1 $2"来实现。

    我爱美国毒品


    上面的答案对我来说都不是完美的,所以必须带上自己的自行车:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    function camelCaseToTitle(camelCase) {
        if (!camelCase) {
            return '';
        }

        var pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.substr(1);
        return pascalCase
            .replace(/([a-z])([A-Z])/g, '$1 $2')
            .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
            .replace(/([a-z])([0-9])/gi, '$1 $2')
            .replace(/([0-9])([a-z])/gi, '$1 $2');
    }

    测试用例:

    1
    2
    3
    4
    5
    6
    null => ''
    '' => ''
    'simpleString' => 'Simple String'
    'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside'
    '
    stringWithNumber123' => 'String With Number 123'
    '
    complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc'


    添加了另一个ES6解决方案,在不满意上面的一些想法之后,我更喜欢它。

    https://codepen.io/902labs/pen/mxdxrv?编辑=0010 0

    1
    2
    3
    4
    5
    6
    const camelize = (str) => str
        .split(' ')
        .map(([first, ...theRest]) => (
            `${first.toUpperCase()}${theRest.join('').toLowerCase()}`)
        )
        .join(' ');