0

I am trying to implement a regex for matching all characters except the first character and any character followed by _ in a single word as:

"HELLO_WORLD".replace(^([A-Z]|/_[A-Z]),f => f.toLowerCase()) // Hello_World

But this is giving me error as :

SyntaxError: Unexpected token ^

Can anybody point whats wrong ? I am following this question basically Regex: match everything but specific pattern

EDIT:

This is happening due to missing string literal but I have a followup question now that my regex is not working as I want.

"HELLO_WORLD".replace(/^([A-Z]|_[A-Z])/,f => f.toLowerCase()) // hELLO_WORLD

This is giving hELLO_WORLD when I want Hello_World

bUff23
  • 163
  • 12

1 Answers1

1

The caret ^ should be inside of the alternation if you want to match either A-Z at the start of the string OR _A-Z in the string.

You are only replacing a single character to lowercase as you are not using the g global flag.

You could use 2 capturing groups using replace instead of 1 where the second capturing group matches 1+ times A-Za-z and that match will be replaced to lowercase.

(^[A-Z]|_[A-Z])([A-Za-z]+)

Regex demo

let result = "HELLO_WOrLD".replace(/(^[A-Z]|_[A-Z])([A-Za-z]+)/g, (_, g1, g2) => g1 + g2.toLowerCase());
console.log(result);
The fourth bird
  • 96,715
  • 14
  • 35
  • 52