0

I have string MetadataCompanyTotal which is Camel Case. I need to insert space between string.

Input is

var str="MetadataCompanyTotal";

output should be

"Metadata Company Total".

I have tried the following approach but needed a faster way with less number of lines as there is lines constraint.

My approach :

var i, 
    str="MetadataCompanyTotal",
    temp_str="",
    final_space_inserted_str="";

for(i=0; i < str.length ; i++){
   if ( str.charAt(i) === str.charAt(i).toUpperCase()){
      final_space_inserted_str += temp_str + " ";//inserting space.
      temp_str = str.charAt(i);
   }
   else{
      temp_str += str.charAt(i);
      }
}


final_space_inserted_str+=temp_str.// last word.

Is there any efficient approach in javascript?

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
Akash Sateesh
  • 271
  • 2
  • 4
  • 13
  • `str.replace(/\B[A-Z]/g, " $&");` replace every uppercase character inside a word with a space + the match *(matched character)* – Thomas Jul 15 '17 at 15:49
  • hanks for the answer. If the input is "MetadataUSAddressType" I wanted the output as 'Metadata US Address Type'. But I am getting 'Metadata U S Address Type'. Is there any way in regex to achieve this. Basically stream of continuous uppercase characters should be grouped – Akash Sateesh Jul 16 '17 at 04:00
  • "continuous uppercase characters should be grouped" You mean `Metadata USAddress Type`? As here "USA" would be the group of uppercase characters. Just fix the result afterwards: `str.replace(/\B[A-Z]/g, " $&").replace(/U S\b/g, v => "US");` – Thomas Jul 16 '17 at 06:08
  • https://stackoverflow.com/questions/30521224/javascript-convert-pascalcase-to-underscore-case --- just replace the underscore with a space – baao Jul 16 '17 at 18:17

2 Answers2

1

Use regex to replace all upper case with space before and trim to remove first space.

var CamelCaseWord = "MetadataUSAddressType";

alert(CamelCaseWord.replace(/([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g, '$1$4 $2$3$5').trim())
Yogen Darji
  • 3,230
  • 16
  • 31
  • Thanks for the answer. If the input is "MetadataUSAddressType" I wanted the output as 'Metadata US Address Type'. But I am getting 'Metadata U S Address Type'. Is there any way in regex to achieve this. Basically stream of continuous uppercase characters should be grouped. – Akash Sateesh Jul 16 '17 at 03:59
  • 1
    you can simplify this to `replace(/\B([A-Z])([A-Z][a-z])|([a-z])([A-Z])/g, '$1$3 $2$4');` and can even get rid of that `trim()` – Thomas Jul 16 '17 at 06:17
0

i Have Another solution

var str = "MetadataCompanyTotal";
var arr = str.split(/(?=[A-Z])/);
var temp = arr.join(" ");
alert(temp);

can look the code here

omer cohen
  • 272
  • 1
  • 4
  • 19