简体   繁体   中英

Javascript Regexp pattern matching

"CamelCase".replace(/[AZ]/g, " $1")

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 /(?!^)[AZ]/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 (ie the CamelCase).

"CamelCaseTestHTML".replace(/([^A-Z])([A-Z])/g, "$1 $2")
// Camel Case Test HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM