Home > front end >  Replacing matched groups differently using ECMAScript (Conditional Replace)
Replacing matched groups differently using ECMAScript (Conditional Replace)

Time:01-21

I want to rename some files using PowerRename using regex.

My files look like this:

hidded_this_should_not_be_hidden

I want the output to be:

this should not be hidden

So I need to match both hidden_ and replace that with nothing, and globally match every occurrence of _, and replace that with .

It was easy using PCRE2. My expression was hidden_|(_) and my substitution ${1: :}. But I simply could not find the equivalent in ECMAScript. Is there any? Every solution I have seen so far requires you to use a function for your substitution, while I can only use pure ECMAScript.

CodePudding user response:

ECMAScript standard does not allow conditional replacement patterns.

See 22.1.3.18.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacementTemplate ) that describes all possible substitution patterns, and the conditional replacement pattern is not on the list of available options.

Keep replacing twice:

  1. Replace hidden_ with an empty string and
  2. Replace _ with .
  • Related