将camelCaseText 转换为Sentence Case Text

IT技术 javascript regex string
2021-01-17 06:57:28

如何在 JavaScript 中将像 'helloThere' 或 'HelloThere' 这样的字符串转换为 'Hello There'?

6个回答

const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);

将第一个字母大写 - 例如。注意 中的空格" $1"


当然,如果第一个字母已经是大写 - 您将有一个空闲空间可以删除。

我在 中挖掘了空格的使用text.replace,我一直在用 2 个以上的参数填充函数调用以提高可读性
2021-03-15 06:57:28
uSBPorts=>USB 端口,不是我所期望的,我想要一个 USB 端口
2021-03-25 06:57:28
进一步以上,那将是这样的: camelToKebab = (str, mode) { let rgx = /defaultRgx/; switch(mode) { 'lower': rgx = /lowerRgx/; break; } ... }
2021-04-04 06:57:28
@signonsridhar 伙计,如果有人将小写字母写usb portsuSBPorts,我会从他们的键盘中窃取 shift 键。我希望它是usbPorts在诸如 之类的情况下theUSA,您可以有一个选项,例如consecutiveCapsMode具有不同模式的lowersplit,例如。然后 docamelToSentence('theUSA', { consecutiveCapsMode: 'lower' })应该返回theUsa,等等。
2021-04-09 06:57:28
写作怎么样Non-GoogleChrome
2021-04-12 06:57:28

或者使用lodash

lodash.startCase(str);

例子:

_.startCase('helloThere');
// ➜ 'Hello There'

Lodash是一个很好的图书馆给快捷方式到许多日常JS tasks.There是许多其他类似的字符串处理函数,例如camelCasekebabCase等等。

每次我认为“lodash 也无法做到这一点”时,它确实做到了。
2021-03-19 06:57:28
@AbhishekKumar startCase of lodash 实际上会转换hello worldHello World lodash.com/docs/4.17.15#upperFirst
2021-03-23 06:57:28
如果您尝试,hello world那么输出应该是Hello There,在这种情况下 loadash 将无济于事。
2021-04-01 06:57:28
你是对的兄弟。我错误地写信hello therehello world.
2021-04-08 06:57:28
从 v4 开始,请注意此函数会删除特殊字符(如 ä)并将它们转换为 ASCII 字符(在本例中为 a)
2021-04-09 06:57:28

我有一个类似的问题,并像这样处理它:

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

要获得更强大的解决方案:

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

http://jsfiddle.net/PeYYQ/

输入:

 helloThere 
 HelloThere 
 ILoveTheUSA
 iLoveTheUSA

输出:

 hello There 
 Hello There 
 I Love The USA
 i Love The USA
此外,它还在单词之间添加了额外的空格
2021-03-21 06:57:28
它在开始时增加了一个额外的空间
2021-04-03 06:57:28
这不是OP所要求的句子情况。第一个字母应该大写。
2021-04-07 06:57:28

没有副作用的例子。

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 中

const camel2title = (camelCase) => camelCase
  .replace(/([A-Z])/g, (match) => ` ${match}`)
  .replace(/^./, (match) => match.toUpperCase())
  .trim();
@DaleZak,迟来的谢谢!一直想找到它,但显然社会机器人固定我...?
2021-03-23 06:57:28
仅供参考,这会在句子的开头添加额外的空格。
2021-04-12 06:57:28
可靠,es6 代码段 +1。
2021-04-13 06:57:28

我发现的用于测试骆驼案例到标题案例函数的最佳字符串是这个荒谬的示例,它测试了很多边缘案例。据我所知,以前发布的函数都没有正确处理这个问题

__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPpersonalIDCardForUser_456InRoom26AContainingABC26TimesNotAsEasyAs123ForC3POOrR2D2Or2R2D

这应该转换为:

及时获得您的 GED 一首关于 26 ABC 的歌曲很重要,但对于 C3PO 或 R2D2 或 2R2D 而言,在 26A 房间内,包含 ABC 26 次的用户 456 个人身份证并不像 123 那样容易

如果您只想要一个简单的函数来处理上述情况(并且比以前的许多答案更多的情况),这是我写的。这段代码不是特别优雅或快速,但它简单、易懂且有效。

下面的代码片段包含一个在线可运行示例:

var mystrings = [ "__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D", "helloThere", "HelloThere", "ILoveTheUSA", "iLoveTheUSA", "DBHostCountry", "SetSlot123ToInput456", "ILoveTheUSANetworkInTheUSA", "Limit_IOC_Duration", "_This_is_a_Test_of_Network123_in_12__days_",  "ASongAboutTheABCsIsFunToSing", "CFDs", "DBSettings", "IWouldLove1Apple", "Employee22IsCool", "SubIDIn",  "ConfigureABCsImmediately", "UseMainNameOnBehalfOfSubNameInOrders" ];

// Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries.
// 
// E.g.:
//    __ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
//                                            --> 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                        --> I 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                         // "__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
            .replace(/(_)+/g, ' ')                              // " ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser 456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
            .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()                                             // "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"
           ;

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

for (var i = 0; i < mystrings.length; i++) {
  jQuery(document.body).append("<br />\"");
  jQuery(document.body).append(camelCaseToTitleCase(mystrings[i]));
  jQuery(document.body).append("\"<br>(was: \"");
  jQuery(document.body).append(mystrings[i]);
  jQuery(document.body).append("\") <br />");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

这是我目前找到的最完整的解决方案。谢谢!
2021-04-04 06:57:28
下划线间隔的测试用例不再起作用,只是提醒一下。添加:.replace(/_/g,' ')解决这个问题。此外,添加 .replace(\&\, ' & ')支持与号拆分
2021-04-06 06:57:28
感谢您指出@JustinDalrymple。我们的内部代码将camelCaseToTitleCase()上面函数封装在了一个处理下划线的辅助函数中,所以我贴的时候没注意到有遗漏。我现在将修复上面的代码。
2021-04-13 06:57:28