nick nick - 13 days ago 5
Javascript Question

Handle exceptions in a function that converts a camelCase string to a Formated String in Javascript

So, I've made a function that converts a

camelCasedString
to a
Properly Formatted String
using some answer here on Stack Overflow.

This is the function:

function camelCaseToString(str){
var a = str.replace( /([A-Z])/g, " $1" );
var b = a.charAt(0).toUpperCase() + a.slice(1);
return b;
}


problem is some outputs are not as I expect them to be, for example, these are wright:

camelCaseToString('exampleText'); // Example Text
camelCaseToString('ExampleText'); // Example Text
camelCaseToString('string(parenthesis)'); //String (parenthesis)


but I expect these:

camelCaseToString('string (Parenthesis)'); //gives String ( Parenthesis)
camelCaseToString('exampleWithRomanNumbersIII'); //gives Example With Roman Numbers I I I


to be
String (Parenthesis)
and
Example With Roman Numbers III
respectively.

Is there a way to to this with Regex? For the parenthesis case, I can simply use
replace('( ', '(')
, but how about the I I I. I need to detect if the Uppercase letters are 1 char long.

I think that this should be really easy to do with Regex but I don't know how to do it. Thanks in advance!

Answer

For your specific test cases this seems to work:

function camelCaseToString(str){
    var a = str.replace( /([^A-Z( ]+)([A-Z(])/g, "$1 $2" );
    var b = a.charAt(0).toUpperCase() + a.slice(1);
    return b;
}