我如何转换字符串既像'helloThere'或'helloThere'到'HelloThere'在JavaScript?
当前回答
连续大写单词的最兼容的答案是:
常量文本 = 'theKD'; const result = text.replace(/([A-Z]{1,})/g, “$1”); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); 控制台.log(最终结果);
它也与KD兼容,不会将其转换为KD。
其他回答
此解决方案也适用于不在[A-Z]范围内的其他Unicode字符。例如:Ä, Ö, Å。
let camelCaseToTitleCase = (s) => (
s.split("").reduce(
(acc, letter, i) => (
i === 0 || console.log(acc, letter, i)
? [...acc, letter.toUpperCase()]
: letter === letter.toUpperCase()
? [...acc, " ", letter]
: [...acc, letter]
), []
).join("")
)
const myString = "ArchipelagoOfÅland"
camelCaseToTitleCase(myString)
好吧,我在这个游戏上晚了几年,但我有一个类似的问题,我想为每一个可能的输入提供一个替换的解决方案。我必须把大部分功劳归功于本帖中的@ZenMaster和本帖中的@Benjamin Udink ten Cate。 代码如下:
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 < textArray.length; i++){
text = textArray[i];
text = text.replace(camelEdges,'$1 ');
text = text.charAt(0).toUpperCase() + text.slice(1);
resultArray.push(text);
}
它有三个子句,都使用了lookahead来防止正则表达式引擎消耗太多字符:
[a-z] (?=[a-z] [a-z])查找一个大写字母,后面跟着一个大写字母,然后是小写字母。这将终结像USA这样的缩写词。 [^ a - z](?=[a - z])查找一个非大写字母后跟一个大写字母。这结束了像myWord这样的单词和像99Bottles这样的符号。 [a- za -z](?=[^a- za -z])查找一个字母后面跟着一个非字母。它以像BFG9000这样的符号前的单词结尾。
这个问题在我的搜索结果的顶部,所以希望我可以为其他人节省一些时间!
const text = 'helloThereMister'; const result = text.replace(/([A-Z])/g, " $1"); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); console.log (finalResult);
第一个字母大写——举个例子。注意“$1”中的空格。
当然,如果第一个字母已经大写了,你就有多余的空间可以删除。
我发现用于测试驼峰式大小写到标题式大小写函数的最佳字符串是这个荒谬的示例,它测试了许多边缘用例。据我所知,之前发布的函数都没有正确地处理这个:
__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
这应该转换为:
一首关于26个ABC的歌曲是很重要的,但是对于26A房间的456号用户来说,一张包含ABC 26倍的个人身份证并不像C3PO或R2D2或2R2D的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>
我也遇到过类似的问题,我是这样处理的:
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
推荐文章
- 我如何使一个HTML文本框显示空时提示?
- 如何隐藏谷歌隐形reCAPTCHA徽章
- 如何测试一个字符串是否包含列表中的一个子字符串,在熊猫?
- 在JavaScript中调换2d数组
- 如何使用JavaScript停止浏览器后退按钮?
- 如何转换/解析从字符串到字符在java?
- 跟踪鼠标位置
- 如何获得<html>标签html与JavaScript / jQuery?
- 浏览器检测JavaScript?
- Javascript臭名昭著的循环问题?
- 在c#中验证字符串只包含字母
- 如何从PHP调用JavaScript函数?
- 不区分大小写的替换
- 好的Python模块模糊字符串比较?
- 不能在呈现不同组件警告时更新组件