Reputation: 311
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?
Upvotes: 0
Views: 72
Reputation: 282
i Have Another solution
var str = "MetadataCompanyTotal";
var arr = str.split(/(?=[A-Z])/);
var temp = arr.join(" ");
alert(temp);
can look the code here
Upvotes: 0
Reputation: 3300
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())
Upvotes: 1