Javascript 将camelCaseText 转换为Sentence Case Text
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7225407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert camelCaseText to Sentence Case Text
提问by HyderA
How can I convert a string either like 'helloThere' or 'HelloThere' to 'Hello There' in JavaScript?
如何在 JavaScript 中将像 'helloThere' 或 'HelloThere' 这样的字符串转换为 'Hello There'?
回答by ZenMaster
var text = 'helloThereMister';
var result = text.replace( /([A-Z])/g, " " );
var finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);
capitalize the first letter - as an example.
大写第一个字母 - 例如。
Note the space in " $1"
.
注意 中的空格" $1"
。
EDIT: added an example of capitalization of the first letter. Of course, in case the first letter is already capital - you would have a spare space to remove.
编辑:添加了第一个字母大写的示例。当然,如果第一个字母已经是大写 - 您将有一个空闲空间可以删除。
回答by Wtower
Alternatively using lodash:
或者使用lodash:
lodash.startCase(str);
Example:
例子:
_.startCase('helloThere');
// ? 'Hello There'
Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase
, kebabCase
etc.
Lodash是一个很好的图书馆给快捷方式到许多日常JS tasks.There是许多其他类似的字符串处理函数,例如camelCase
,kebabCase
等等。
回答by James Khoury
I had a similar problem and dealt with it like this:
我有一个类似的问题,并像这样处理它:
stringValue.replace(/([A-Z]+)*([A-Z][a-z])/g, " ")
For a more robust solution:
要获得更强大的解决方案:
stringValue.replace(/([A-Z]+)/g, " ").replace(/([A-Z][a-z])/g, " ")
Input:
输入:
helloThere
HelloThere
ILoveTheUSA
iLoveTheUSA
Output:
输出:
hello There
Hello There
I Love The USA
i Love The USA
回答by renevanderark
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
在 ES6 中
const camel2title = (camelCase) => camelCase
.replace(/([A-Z])/g, (match) => ` ${match}`)
.replace(/^./, (match) => match.toUpperCase());
回答by Chris Kline
The best string I've found for testing camel-case-to-title-case functions is this ridiculously nonsensical example, which tests a lot of edge cases. To the best of my knowledge, none of the previously posted functions handle this correctly:
我发现的用于测试骆驼案例到标题案例函数的最佳字符串是这个荒谬的例子,它测试了很多边缘案例。据我所知,以前发布的函数都没有正确处理这个问题:
ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
To Get Your GEDInTimeASong About The26ABCsIsOfTheEssenceButAPpersonalIDCardForUser456InRoom26AContainingABC26TimesNotAsEasyAs123ForC3POOrR2D2Or2R2D
This should be converted to:
这应该转换为:
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
及时获得您的 GED 一首关于 26 ABC 的歌曲很重要,但对于 C3PO 或 R2D2 或 2R2D 而言,在 26A 房间的用户 456 包含 ABC 26 次的个人身并不像 123 那样容易
If you want just a simple function that handles cases like the one above (and more cases than many of the previously answers), here's the one I wrote. This code isn't particularly elegant or fast, but it's simple, understandable, and works.
如果您只需要一个简单的函数来处理上述情况(并且比以前的许多答案都多),那么这就是我写的。这段代码不是特别优雅或快速,但它简单、易懂且有效。
An online runnable example is on jsfiddle, or you can view the output of the snippet below in your console:
jsfiddle 上有一个在线可运行示例,或者您可以在控制台中查看以下代码段的输出:
// Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries.
//
// E.g.:
var examples = [
'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, " ") // "To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times IsNot AsEasy As123ForC3POOrR2D2Or2R2D"
.replace(/([A-Z][a-z])([A-Z])/g, " ") // "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, " ") // "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, " ") // "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, " ") // "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, " ") // "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, " ") // "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, " ") // "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, " ") // "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);
}
examples.forEach(str => console.log(str, ' --> \n', camelCaseToTitleCase(str)));
Alternately, as user Barno suggested, using SugarJSis an easy solution if you don't mind pulling in that library. I am not sure if it handles the test string I describe above, however; I haven't tried it on that input.
或者,正如用户 Barno 建议的那样,如果您不介意引入该库,则使用SugarJS是一个简单的解决方案。但是,我不确定它是否处理我上面描述的测试字符串;我还没有在那个输入上试过。
回答by Anthony S.
Based on one of the examples above I came up with this:
基于上面的例子之一,我想出了这个:
const camelToTitle = (camelCase) => camelCase
.replace(/([A-Z])/g, (match) => ` ${match}`)
.replace(/^./, (match) => match.toUpperCase())
.trim()
It works for me because it uses .trim()
to handle the edge case where the first letter is capitalized and you end up with a extra leading space.
它对我有用.trim()
,因为它用于处理第一个字母大写并且最终有一个额外的前导空格的边缘情况。
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
回答by asafd
Here's my version of it. It adds a space before every UpperCase english letter that comes after a lowercase english letter and also capitalizes the first letter if needed:
这是我的版本。它在小写英文字母之后的每个大写英文字母之前添加一个空格,并在需要时将第一个字母大写:
For example:
thisIsCamelCase --> This Is Camel Case
this IsCamelCase --> This Is Camel Case
thisIsCamelCase123 --> This Is Camel Case123
例如:
thisIsCamelCase --> 这是骆驼案例
this IsCamelCase --> 这是骆驼案例
thisIsCamelCase123 --> 这是骆驼案例123
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;
}
回答by Christopher Smith
Ok, I'm a few years late to the game, but I had a similar question, and I wanted to make a one-replace solution for every possible input. I must give most of the credit to @ZenMaster in this thread and @Benjamin Udink ten Cate in thisthread. Here's the code:
好吧,我迟到了几年,但我有一个类似的问题,我想为每个可能的输入制作一个一次性解决方案。我必须给大部分的功劳要@ZenMaster该线程和@Benjamin Udink十大美食在这个线程。这是代码:
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,' ');
text = text.charAt(0).toUpperCase() + text.slice(1);
resultArray.push(text);
}
It has three clauses, all using lookaheadto prevent the regex engine from consuming too many characters:
它有三个子句,都使用前瞻来防止正则表达式引擎消耗太多字符:
[A-Z](?=[A-Z][a-z])
looks for a capital letter that is followed by a capital then a lowercase. This is to end acronyms like USA.[^A-Z](?=[A-Z])
looks for a non-capital-letter followed by a capital letter. This ends words like myWord and symbols like 99Bottles.[a-zA-Z](?=[^a-zA-Z])
looks for a letter followed by a non-letter. This ends words before symbols like BFG9000.
[A-Z](?=[A-Z][a-z])
查找大写字母,后跟大写字母,然后是小写字母。这是为了结束像美国这样的首字母缩略词。[^A-Z](?=[A-Z])
查找非大写字母后跟大写字母。这结束了像 myWord 这样的词和像 99Bottles 这样的符号。[a-zA-Z](?=[^a-zA-Z])
查找后跟非字母的字母。这在 BFG9000 等符号之前结束单词。
This question was at the top of my search results, so hopefully I can save others some time!
这个问题在我搜索结果的顶部,所以希望我可以为其他人节省一些时间!
回答by Dipu
This implementation takes consecutive uppercase letters and numbers in consideration.
此实现考虑了连续的大写字母和数字。
function camelToTitleCase(str) {
return str
.replace(/[0-9]{2,}/g, match => ` ${match} `)
.replace(/[^A-Z0-9][A-Z]/g, match => `${match[0]} ${match[1]}`)
.replace(/[A-Z][A-Z][^A-Z0-9]/g, match => `${match[0]} ${match[1]}${match[2]}`)
.replace(/[ ]{2,}/g, match => ' ')
.replace(/\s./g, match => match.toUpperCase())
.replace(/^./, match => match.toUpperCase())
.trim();
}
// ----------------------------------------------------- //
var testSet = [
'camelCase',
'camelTOPCase',
'aP2PConnection',
'superSimpleExample',
'aGoodIPAddress',
'goodNumber90text',
'bad132Number90text',
];
testSet.forEach(function(item) {
console.log(item, '->', camelToTitleCase(item));
});
Expected output:
预期输出:
camelCase -> Camel Case
camelTOPCase -> Camel TOP Case
aP2PConnection -> A P2P Connection
superSimpleExample -> Super Simple Example
aGoodIPAddress -> A Good IP Address
goodNumber90text -> Good Number 90 Text
bad132Number90text -> Bad 132 Number 90 Text
回答by jfriend00
You can use a function like this:
您可以使用这样的函数:
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"
Code with a bunch of test strings here: http://jsfiddle.net/jfriend00/FWLuV/.
这里有一堆测试字符串的代码:http: //jsfiddle.net/jfriend00/FWLuV/。
Alternate version that keeps leading spaces here: http://jsfiddle.net/jfriend00/Uy2ac/.
在此处保留领先空格的替代版本:http: //jsfiddle.net/jfriend00/Uy2ac/。