我如何转换字符串既像'helloThere'或'helloThere'到'HelloThere'在JavaScript?
const text = 'helloThereMister'; const result = text.replace(/([A-Z])/g, " $1"); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); console.log (finalResult);
第一个字母大写——举个例子。注意“$1”中的空格。
当然,如果第一个字母已经大写了,你就有多余的空间可以删除。
我也遇到过类似的问题,我是这样处理的:
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
你可以使用这样的函数:
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/。
试试这个库
http://sugarjs.com/api/String/titleize
'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"
这是我的版本。它在每个小写英文字母后面的大写英文字母之前增加一个空格,如果需要,还会将第一个字母大写:
例如: This IsCamelCase——> This IsCamelCase 这是骆驼案——>这是骆驼案 This IsCamelCase123——>
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。 代码如下:
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这样的符号前的单词结尾。
这个问题在我的搜索结果的顶部,所以希望我可以为其他人节省一些时间!
上面的答案对我来说都不完美,所以我不得不带着自己的自行车:
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');
}
测试用例:
null => ''
'' => ''
'simpleString' => 'Simple String'
'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside'
'stringWithNumber123' => 'String With Number 123'
'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc'
我发现用于测试驼峰式大小写到标题式大小写函数的最佳字符串是这个荒谬的示例,它测试了许多边缘用例。据我所知,之前发布的函数都没有正确地处理这个:
__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>
这个对我有用看看这个
CamelcaseToWord(“名字”);//返回我的名字
function CamelcaseToWord(string){
return string.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
}
或者使用lodash:
lodash.startCase(str);
例子:
_.startCase('helloThere');
// ➜ 'Hello There'
Lodash是一个很好的库,可以为许多日常的js任务提供快捷方式。还有许多其他类似的字符串操作函数,如camelCase, kebabCase等。
没有副作用的例子。
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();
我没有尝试每个人的答案,但我修补过的几个解决方案并不能满足我所有的要求。
我想出了一个办法…
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(),
'')
添加了另一个ES6解决方案,我更喜欢上面的一些想法。
https://codepen.io/902Labs/pen/mxdxRv?editors=0010#0
const camelize = (str) => str
.split(' ')
.map(([first, ...theRest]) => (
`${first.toUpperCase()}${theRest.join('').toLowerCase()}`)
)
.join(' ');
下面是使用正则表达式演示驼峰大小写字符串到句子字符串的链接。
输入
myCamelCaseSTRINGToSPLITDemo
输出
我的骆驼案例字符串分裂演示
这是一个将驼峰格式转换为句子文本的正则表达式
(?=[A-Z][a-z])|([A-Z]+)([A-Z][a-rt-z][a-z]\*)
用1美元2美元代替。
单击可查看正则表达式的转换
基于上面的一个例子,我想出了这个:
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
输入 javaScript
输出 Java脚本
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");
这种实现需要考虑连续的大写字母和数字。
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)); });
预期的输出:
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
另一个基于RegEx的解决方案。
respace(str) {
const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
return str.replace(regex, '$& ');
}
解释
上面的正则表达式由两个相似的部分组成,由OR运算符分开。前半部分:
([A-Z]) -匹配大写字母… (?=[a-z] [a-z]) -后面跟着一个大写字母和小写字母的序列。
当应用于序列FOo时,它有效地匹配它的F字母。
或者第二种情况:
([a-z]) -匹配小写字母… (?=[A-Z]) -后面跟着一个大写字母。
当应用于序列barFoo时,它有效地匹配了它的r字母。
当找到所有替换候选时,最后要做的事情是用相同的字母替换它们,但要使用额外的空格字符。为此,我们可以使用'$& '作为替换,它将解析为一个匹配的子字符串,后面跟着一个空格字符。
例子
const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']
testWords.map(w => w.replace(regex, '$& '))
->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]
如果你处理的是大写骆驼的情况,这个片段可以帮助你,它还包含一些规格,所以你可以确保它适合你的情况。
export const fromCamelCaseToSentence = (word) =>
word
.replace(/([A-Z][a-z]+)/g, ' $1')
.replace(/([A-Z]{2,})/g, ' $1')
.replace(/\s{2,}/g, ' ')
.trim();
和规格:
describe('fromCamelCaseToSentence', () => {
test('does not fall with a single word', () => {
expect(fromCamelCaseToSentence('Approved')).toContain('Approved')
expect(fromCamelCaseToSentence('MDA')).toContain('MDA')
})
test('does not fall with an empty string', () => {
expect(fromCamelCaseToSentence('')).toContain('')
})
test('returns the separated by space words', () => {
expect(fromCamelCaseToSentence('NotApprovedStatus')).toContain('Not Approved Status')
expect(fromCamelCaseToSentence('GDBState')).toContain('GDB State')
expect(fromCamelCaseToSentence('StatusDGG')).toContain('Status DGG')
})
})
卧底C程序员。如果你像我一样想保留首字母缩略词,不想看神秘的模式,那么你可能会喜欢这个:
function isUpperCase (str) {
return str === str.toUpperCase()
}
export function camelCaseToTitle (str) {
for (let i = str.length - 1; i > 0; i--) {
if (!isUpperCase(str[i - 1]) && isUpperCase(str[i])) {
str = str.slice(0, i) + ' ' + str.slice(i)
}
}
return str.charAt(0).toUpperCase() + str.slice(1)
}
使用JS的String.prototype.replace()和String.prototype.toUpperCase()
const str = "thisIsATestString"; const res = str.replace (/ ^ [a - z] | [a - z] / g (c i) = >(我吗?": "") + c.toUpperCase()); console.log (res);// "This Is A Test String"
连续大写单词的最兼容的答案是:
常量文本 = '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)
我的分裂案例解决方案的行为方式,我想:
const splitCase = s => !s || s.indexOf(' ') >= 0 ? s :
(s.charAt(0).toUpperCase() + s.substring(1))
.split(/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g)
.map(x => x.replace(/([0-9]+)/g,'$1 '))
.join(' ')
输入
'a,abc,TheId,TheID,TheIDWord,TheID2Word,Leave me Alone!'
.split(',').map(splitCase)
.forEach(x => console.log(x))
输出
A
Abc
The Id
The ID
The ID Word
The ID2 Word
Leave me Alone!
由于上述函数需要在JS中使用Lookbehind,而目前Safari中还没有实现,因此我重写了实现,以不使用下面的RegEx:
const isUpper = c => c >= 'A' && c <= 'Z'
const isDigit = c => c >= '0' && c <= '9'
const upperOrDigit = c => isUpper(c) || isDigit(c)
function splitCase(s) {
let to = []
if (typeof s != 'string') return to
let lastSplit = 0
for (let i=0; i<s.length; i++) {
let c = s[i]
let prev = i>0 ? s[i-1] : null
let next = i+1 < s.length ? s[i+1] : null
if (upperOrDigit(c) && (!upperOrDigit(prev) || !upperOrDigit(next))) {
to.push(s.substring(lastSplit, i))
lastSplit = i
}
}
to.push(s.substring(lastSplit, s.length))
return to.filter(x => !!x)
}
HTTPRequest_ToServer-AndWaiting --> HTTP Request To Server And Waiting
function toSpaceCase(str) { return str .replace(/[-_]/g, ' ') /* * insert a space between lower & upper * HttpRequest => Http Request */ .replace(/([a-z])([A-Z])/g, '$1 $2') /* * space before last upper in a sequence followed by lower * XMLHttp => XML Http */ .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3') // uppercase the first character .replace(/^./, str => str.toUpperCase()) .replace(/\s+/g, ' ') .trim(); } const input = 'HTTPRequest_ToServer-AndWaiting'; const result = toSpaceCase(input); console.log(input,'-->', result)
推荐文章
- 在setInterval中使用React状态钩子时状态不更新
- 使用JavaScript显示/隐藏'div'
- 使用JavaScript获取所选的选项文本
- 在bash中使用正则表达式进行搜索和替换
- AngularJS模板中的三元运算符
- 让d3.js可视化布局反应灵敏的最好方法是什么?
- 原型的目的是什么?
- 如何正确比较C中的字符串?
- 如何将CharSequence转换为字符串?
- 检查jquery是否使用Javascript加载
- 将camelCaseText转换为标题大小写文本
- 如何在JavaScript客户端截屏网站/谷歌怎么做的?(无需存取硬盘)
- string.Equals()和==运算符真的一样吗?
- 如何在JavaScript中遍历表行和单元格?
- jQuery map vs. each