开发者

Javascript Regexp pattern matching

"CamelCase".replace(/[A-Z]/g, " $1")开发者_C百科

Produces

>>" $1amel $1ase"

How to replace all occurrence of camel cases.


You need bracket ( ) for grouping

"CamelCase".replace(/([A-Z])/g, " $1")

produces

 Camel Case


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"


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜