Convert camelCaseText to sentence text

How can I convert a string like "helloThere" or "HelloThere" to "Hello There" in JavaScript?

+113
javascript string regex
Aug 29 '11 at 2:03
source share
17 answers
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. 

Note the space in " $1" .

EDIT: Added an example of capitalizing the first letter. Of course, if the first letter is already capital, you will have free space for deletion.

+137
Aug 29 '11 at 2:11
source share
β€” -

Alternatively using lodash :

 lodash.startCase(str); 

Example:

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

Lodash is a great library that provides a shortcut to many everyday js tasks. There are many other similar string manipulation functions like camelCase , kebabCase , etc.

+81
Jul 28 '16 at 11:49
source share

I had a similar problem and dealt with this as follows:

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

For a more reliable solution:

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

http://jsfiddle.net/PeYYQ/

Input:

  helloThere HelloThere ILoveTheUSA iLoveTheUSA 

Output:

  hello There Hello There I Love The USA i Love The USA 
+45
Aug 29 '11 at 2:17
source share

An example without side effects.

 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(); }); } 

In ES6

 const camel2title = (camelCase) => camelCase .replace(/([AZ])/g, (match) => ` ${match}`) .replace(/^./, (match) => match.toUpperCase()); 
+25
Sep 27 '16 at 7:32
source share

The best line I've found to test camel case-title-case features is a ridiculously ridiculous example that tests a lot of extreme cases. As far as I know, none of the previously published functions handled this correctly :

ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D

This should be converted to:

To get the GED on time, a 26 ABC song is essential, but a personal identification card for user 456 in room 26A containing 26 ABCs is not as simple as 123 for C3PO or R2D2 or 2R2D

If you want just a simple function that handles cases like the above (and more cases than many of the previous answers), here is the one I wrote. This code is not very elegant and not fast, but it is simple, understandable and works.

An online example of this is here: http://jsfiddle.net/q5gbye2w/56/

 // Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries. // // Eg: // 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(/([az])([AZ][az])/g, "$1 $2") // "To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times IsNot AsEasy As123ForC3POOrR2D2Or2R2D" .replace(/([AZ][az])([AZ])/g, "$1 $2") // "To Get YourGEDIn TimeASong About The26ABCs Is Of The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D" .replace(/([az])([AZ]+[az])/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(/([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 User456In Room26A ContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D" .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 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, 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 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D" .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 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(/([AZ]{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,})([AZ]{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(); // capitalize the first letter return result.charAt(0).toUpperCase() + result.slice(1); } 

Alternatively, as suggested by the Barno user , using SugarJS is a simple solution if you do not mind using this library. However, I'm not sure if it handles the test string that I described above; I have not tried this on this entry.

+11
Mar 12 '16 at 3:14
source share

Here is my version. It adds a space before each UpperCase English letter that appears after a lowercase English letter, and also uses the first letter if necessary:

For example:
thisIsCamelCase β†’ This is a camel case
IsCamelCase β†’ This is the work of the camel
thisIsCamelCase123 β†’ This Is 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; } 
+9
May 26 '14 at 13:47
source share

Well, I was late for a few years in the game, but I had a similar question, and I wanted to make a one-task solution for every possible input. I have to give most of the credit @ZenMaster in this thread and @Benjamin Udink ten Cate in this thread. Here is the code:

 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); } 

It has three sentences: all using lookahead to prevent the regex engine from consuming too many characters:

  • [AZ](?=[AZ][az]) searches for a capital letter, followed by capital, and then lowercase. This should mean a reduction in acronyms such as the United States.
  • [^AZ](?=[AZ]) looking for a non-classical letter followed by a capital letter. It ends with words like myWord and characters like 99Bottles.
  • [a-zA-Z](?=[^a-zA-Z]) looking for a letter followed by not a letter. This ends with the words before characters like BFG9000.

This question was at the top of my search results, so hopefully I can save some more time!

+7
Jan 08 '16 at 15:49
source share

Based on one of the examples above, I came up with the following:

 const camelToTitle = (camelCase) => camelCase .replace(/([AZ])/g, (match) => ' ${match}') .replace(/^./, (match) => match.toUpperCase()) .trim() 

This works for me, because it uses .trim() to handle the extreme case where the first letter is .trim() and you have an extra leading space.

Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

+6
Oct. 01
source share

You can use this 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" 

Code with a bunch of test lines here: http://jsfiddle.net/jfriend00/FWLuV/ .

An alternative version in which leading spaces are stored: http://jsfiddle.net/jfriend00/Uy2ac/ .

+3
Aug 29 '11 at 2:18
source share

try this library

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" 
+2
Feb 20 '14 at 15:38
source share

It works for me, check it out

CamelcaseToWord ("MyName"); // returns My Name

  function CamelcaseToWord(string){ return string.replace(/([AZ]+)/g, " $1").replace(/([AZ][az])/g, " $1"); } 
+2
Jun 23 '16 at 12:10
source share

I think this can only be done with reg exp /([az]|[AZ]+)([AZ])/g and replacing "$1 $2" .

ILoveTheUSADope β†’ I love US drugs

+2
Sep 23 '18 at 0:11
source share

None of the answers above worked perfectly for me, so I had to ride with my own bike:

 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'); } 

Test cases:

 null => '' '' => '' 'simpleString' => 'Simple String' 'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside' 'stringWithNumber123' => 'String With Number 123' 'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc' 
+1
Feb 12 '16 at 12:27
source share

I did not try to answer everyone, but several of the solutions that I was messing around did not meet all my requirements.

I was able to come up with something I did ...

 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(), '') 
+1
Oct 21 '16 at 10:20
source share

Below is a link that shows a camel line in a sentence line using regular expressions.

Input

myCamelCaseSTRINGToSPLITDemo

Exit

my Camel Case STRING To SPLIT Demo




This is a regular expression for converting a camel case to sentence text.

 (?=[AZ][az])|([AZ]+)([AZ][a-rt-z][az]\*) 

with $1 $2 as a replacement.

Click to view regex conversion

+1
Jun 21 '18 at 12:51
source share

Input

JavaScript Java Script Output

  var text = 'javaScript'; text.replace(/([az])([AZ][az])/g, "$1 $2").charAt(0).toUpperCase()+text.slice(1).replace(/([az])([AZ][az])/g, "$1 $2"); 
0
Aug 19 '19 at 11:31 on
source share

Add another ES6 solution that I liked more after I was not happy with a few thoughts above.

https://codepen.io/902Labs/pen/mxdxRv?editors=0010#0

 const camelize = (str) => str .split(' ') .map(([first, ...theRest]) => ( '${first.toUpperCase()}${theRest.join('').toLowerCase()}') ) .join(' '); 
-one
Mar 09 '18 at 2:54
source share



All Articles