Home > Software engineering >  How to change the regex so it match function calls in the string?
How to change the regex so it match function calls in the string?

Time:02-03

I want to add optional property access expressions in the string, including function calls.

For example, for each input in the array, the output should be like in the comment.

const inputs = [
  'foo', //foo
  'foo.bar', //foo.bar
  'foo.bar.baz', // foo.bar?.baz
  'bla.some()', // bla.some?.()
  'bla.bar.you()', // bla.bar?.you?.()
  'account === prop.account.id', // account === prop.account?.id
  '{ myclass: foo.bar.baz }', // { myclass: foo.bar?.baz }
];

So to do that I create a regex: /(\w )\.(?!\?)/g, which mean after a word with . match the next prop add add ? using replace method:

const input = "foo.bar.baz.you";
const output = input.replace(/(?<=\w \.)(\w )\.(?!\?)/g, "$1?.");
console.log(output); // foo.bar?.baz?.you

it works for property access only and I want to add also for function calls: bla.some()

const inputs = [
  'foo', //foo
  'foo.bar', //foo.bar
  'foo.bar.baz', // foo.bar?.baz
  'bla.some()', // bla.some?.()
  'bla.bar.you()', // bla.bar?.you?.()
  'account === prop.account.id', // account === prop.account?.id
  '{ myclass: foo.bar.baz }', // { myclass: foo.bar?.baz }
];

inputs.slice(0, 20).forEach((f) => {

  const output = f.replace(/(?<=\w \.)(\w )\.(?!\?)/g, '$1?.');
  console.log(output);
});

How I can change that regex so it match also to function calls?

CodePudding user response:

Use replacement function which will be invoked after a match has been performed to check if it matches interim property (.prop.) or a function call (.func()):

const inputs = [
    'foo', //foo
    'foo.bar', //foo.bar
    'foo.bar.baz', // foo.bar?.baz
    'bla.some()', // bla.some?.()
    'bla.bar.you()', // bla.bar?.you?.()
    'account === prop.account.id', // account === prop.account?.id
    '{ myclass: foo.bar.baz }', // { myclass: foo.bar?.baz }
];

inputs.slice(0, 20).forEach((f) => {
    const output = f.replace(/(?<=\w \.\w )(\.|\(\))/g, function(m) {
        return '?'   (m == '()' ? '.' : '')   m;
    });
    console.log(output);
});

  • Related