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
146k22 gold badges162 silver badges181 bronze badges
asked Jul 15, 2017 at 15:38
Akash Sateesh
3112 gold badges4 silver badges13 bronze badges
2 Answers 2
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())
answered Jul 15, 2017 at 15:42
Yogen Darji
3,31018 silver badges31 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Akash Sateesh
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.
Thomas
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()i Have Another solution
var str = "MetadataCompanyTotal";
var arr = str.split(/(?=[A-Z])/);
var temp = arr.join(" ");
alert(temp);
can look the code here
answered Jul 16, 2017 at 18:28
omer cohen
2821 gold badge5 silver badges19 bronze badges
Comments
lang-js
str.replace(/\B[A-Z]/g, " $&");replace every uppercase character inside a word with a space + the match (matched character)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");