Reputation: 4143
"CamelCase".replace(/[A-Z]/g, " $1")
Produces
>>" $1amel $1ase"
How to replace all occurrence of camel cases.
Upvotes: 2
Views: 1641
Reputation: 51970
Maybe I'm missing something obvious but the previous answers do not act on CamelCased content but rather on all occurrences of uppercase letters.
This example preserves continuous blocks of capital letters and only separates a non-uppercase-letter followed by an uppercase letter (i.e. the CamelCase).
"CamelCaseTestHTML".replace(/([^A-Z])([A-Z])/g, "$1 $2")
// Camel Case Test HTML
Upvotes: 1
Reputation: 655825
You don’t need to use a group. Use $&
to reference the whole match:
"CamelCase".replace(/[A-Z]/g, " $&")
And when using /(?!^)[A-Z]/g
instead, you won’t get that leading space:
"CamelCase".replace(/(?!^)[A-Z]/g, " $&") === "Camel Case"
Upvotes: 2
Reputation: 123937
You need bracket ( ) for grouping
"CamelCase".replace(/([A-Z])/g, " $1")
produces
Camel Case
Upvotes: 2