Justin
Justin

Reputation: 45330

String length of regular expression capture group (JavaScript)

Is it possible to get the string length of a regular expression capture group in JavaScript? I want to replace the length of the actual password capture group (which is $2) with asterisks.

let urlRedacted = url.replace(/mongodb:\/\/(.+):(.+)@(.+)/, 'mongodb://$1:*****@$3');

Above it is just replacing with hardcoded five ***** instead of the actual length of the password ($2).

Upvotes: 1

Views: 378

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

No need for a lambda if you can use lookbehind:

const url = 'mongodb://foo:bar@baz';
let urlRedacted = url.replace(/(?<=mongodb:\/\/.+:[^@]*)[^@]/g, '*');
console.log(urlRedacted); // mongodb://foo:***@baz

See proof.

Explanation

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    mongodb:                 'mongodb:'
--------------------------------------------------------------------------------
    \/                       '/'
--------------------------------------------------------------------------------
    \/                       '/'
--------------------------------------------------------------------------------
    .+                       any character except \n (1 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    :                        ':'
--------------------------------------------------------------------------------
    [^@]*                    any character except: '@' (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  [^@]                     any character except: '@'

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370679

Use a callback function to get the second group into a variable, then .replace the group with all *s:

const url = 'mongodb://foo:bar@baz';

const censor = str => str.replace(/./g, '*');
// could also do
// const censor = str => '*'.repeat(str.length);
let urlRedacted = url.replace(
  /mongodb:\/\/(.+):(.+)@(.+)/,
  (_, g1, g2, g3) => `mongodb://${g1}:${censor(g2)}@${g3}`
);

console.log(urlRedacted);

Upvotes: 2

Related Questions