将camelCaseText转换为骆驼案例文本

如何在Javascript中将string转换为“HelloThere”或“HelloThere”以“Hello There”

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

请注意" $1"的空格。

编辑:增加了第一个字母的大写的例子。 当然,如果第一个字母已经是大写字母了 – 你将有一个空余的空间来删除​​。

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

 stringValue.replace(/([AZ]+)*([AZ][az])/g, "$1 $2") 

为了更强大的解决scheme:

 stringValue.replace(/([AZ]+)/g, " $1").replace(/([AZ][az])/g, " $1") 

http://jsfiddle.net/PeYYQ/

input:

  helloThere HelloThere ILoveTheUSA iLoveTheUSA 

输出:

  hello There Hello There I Love The USA i Love The USA 

或者使用lodash :

 lodash.startCase(str); 

例:

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

Lodash是一个很好的图书馆,可以给许多日常的js任务提供捷径。还有许多其他类似的string处理函数,如camelCasekebabCase

这是我的版本。 它在小写英文字母后面的每个UpperCase英文字母之前添加一个空格,并且在需要时还首字母大写:

例如:
thisIsCamelCase – >这是骆驼案件
这是IsCamelCase – >这是骆驼案件
thisIsCamelCase123 – >这是Camel Case123

  function camelCaseToTitleCase(camelCase){ if (camelCase == null || camelCase == "") { return camelCase; } camelCase = camelCase.trim(); var newText = ""; for (var i = 0; i < camelCase.length; i++) { if (/[AZ]/.test(camelCase[i]) && i != 0 && /[az]/.test(camelCase[i-1])) { newText += " "; } if (i == 0 && /[az]/.test(camelCase[i])) { newText += camelCase[i].toUpperCase(); } else { newText += camelCase[i]; } } return newText; } 

没有副作用的例子。

 function camel2title(camelCase) { // no side-effects return camelCase // inject space before the upper case letters .replace(/([AZ])/g, function(match) { return " " + match; }) // replace first char with upper case .replace(/^./, function(match) { return match.toUpperCase(); }); } 

在ES6中

 const camel2title = (camelCase) => camelCase .replace(/([AZ])/g, (match) => ` ${match}`) .replace(/^./, (match) => match.toUpperCase()); 

好吧,我已经晚了几年,但是我有一个类似的问题,我想为每一个可能的input做一个replace解决scheme。 在这个线程中,我必须把@ZenMaster的大部分功劳和@Benjamin Udink ten Cate放在这个线程中。 代码如下:

 var camelEdges = /([AZ](?=[AZ][az])|[^AZ](?=[AZ])|[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来防止正则expression式引擎消耗太多的字符:

  1. [AZ](?=[AZ][az])查找大写字母,然后是大写字母,然后是小写字母。 这是结束像美国这样的缩略词。
  2. [^AZ](?=[AZ])查找非大写字母后跟大写字母。 这结束了像myWord这样的词和象99Bottles的符号。
  3. [a-zA-Z](?=[^a-zA-Z])查找一个字母后跟一个非字母。 这就像BFG9000之类的符号之前的单词。

这个问题是我的search结果的顶部,所以希望我可以节省一些时间!

正如用户Barno所build议的那样 ,如果您不介意拉入该库,那么使用SugarJS是一个非常强大和简单的解决scheme。

如果你只需要一个简单的函数来处理大多数情况(以及比以前的答案更多的情况),下面是我使用的一个。

我发现的用于testing骆驼大小写的函数的最好的string就是这个荒谬无味的例子,它testing了很多边界情况:

ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456ContainingABC26TimesIsNotAsEasyAs123

这应该被转换为:

要及时获得GED关于26 ABC的歌是本质的,但一个用户的个人身份证456包含ABC 26次并不像123那么简单

据我所知,以前发布的函数都没有正确处理这个问题。

这是一些代码来做到这一点。 这个代码不是特别优雅或者快速,但是它很简单,很有效。

 // Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries. // // Eg: // 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 // ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456ContainingABC26TimesIsNotAsEasyAs123 // --> To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 Containing ABC 26 Times Is Not As Easy As 123 // function camelCaseToTitleCase(in_camelCaseString) { var result = in_camelCaseString // "ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456ContainingABC26TimesIsNotAsEasyAs123" .replace(/([az])([AZ][az])/g, "$1 $2") // "To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456ContainingABC26Times IsNot AsEasy As123" .replace(/([AZ][az])([AZ])/g, "$1 $2") // "To Get YourGEDIn TimeASong About The26ABCs Is Of The Essence ButAPersonalIDCard For User456ContainingABC26Times Is Not As Easy As123" .replace(/([az])([AZ]+[az])/g, "$1 $2") // "To Get Your GEDIn Time ASong About The26ABCs Is Of The Essence But APersonal IDCard For User456ContainingABC26Times Is Not As Easy As123" .replace(/([AZ]+)([AZ][az][az])/g, "$1 $2") // "To Get Your GEDIn Time A Song About The26ABCs Is Of The Essence But A Personal ID Card For User456ContainingABC26Times Is Not As Easy As123" .replace(/([az]+)([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 456Containing ABC26Times Is Not As Easy As 123" // Note: the next regex includes a special case to exclude plurals of acronyms, eg "ABCs" .replace(/([AZ]+)([AZ][a-rt-z][az]*)/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 456Containing ABC26Times Is Not As Easy As 123" .replace(/([0-9])([AZ][az]+)/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 Containing ABC26 Times Is Not As Easy As 123" .replace(/([AZ]+)([0-9]+)/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 Containing ABC 26 Times Is Not As Easy As 123" .replace(/([0-9]+)([AZ]+)/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 Containing ABC 26 Times Is Not As Easy As 123" .trim(); // capitalize the first letter return result.charAt(0).toUpperCase() + result.slice(1); } 

试试这个库

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" 

你可以使用这样的function:

 function fixStr(str) { var out = str.replace(/^\s*/, ""); // strip leading spaces out = out.replace(/^[az]|[^\s][AZ]/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" 

用一堆testingstring代码在这里: http : //jsfiddle.net/jfriend00/FWLuV/ 。

保持领先空间的替代版本: http : //jsfiddle.net/jfriend00/Uy2ac/ 。

这对我工作检查了这一点

CamelcaseToWord( “MYNAME”); //返回我的名字

  function CamelcaseToWord(string){ return string.replace(/([AZ]+)/g, " $1").replace(/([AZ][az])/g, " $1"); } 

上面的答案都没有为我完美的工作,所以不得不用自己的自行车来:

 function camelCaseToTitle(camelCase) { if (!camelCase) { return ''; } var pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.substr(1); return pascalCase .replace(/([az])([AZ])/g, '$1 $2') .replace(/([AZ])([AZ][az])/g, '$1 $2') .replace(/([az])([0-9])/gi, '$1 $2') .replace(/([0-9])([az])/gi, '$1 $2'); } 

testing用例:

 null => '' '' => '' 'simpleString' => 'Simple String' 'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside' 'stringWithNumber123' => 'String With Number 123' 'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc' 

我没有尝试每个人的答案,但是我提出的几个解决scheme并不符合我的所有要求。

我能够想出一些做…

 export const jsObjToCSSString = (o={}) => Object.keys(o) .map(key => ({ key, value: o[key] })) .map(({key, value}) => ({ key: key.replace( /([AZ])/g, "-$1").toLowerCase(), value }) ) .reduce( (css, {key, value}) => `${css} ${key}: ${value}; `.trim(), '')