Jon Sud
Jon Sud

Reputation: 11651

How to match and find the function calling from the string using regex in js?

I have a string containing expressions such as calling to functions and properties:

$ctrl.accounts $ctrl.fn() $ctrl.fns(arg) $ctrl.foo.bar $ctrl.bay.bag() $ctrl.bar.fn(arg)

I made this regex that matches the word after $ctrl.: /(?<=\$ctrl\.)[a-zA-Z]+(?=\s|\.|\(|$)/g. This matches the property or the function without . or (. (?=\s|\.|\(|$).

The output of this string against this regex would be:

"accounts", "fn", "fns", "foo", "bay", "bar"

That's working as expected:

const input = `$ctrl.accounts $ctrl.fn() $ctrl.fns(arg) $ctrl.foo.bar $ctrl.bay.bag() $ctrl.bar.fn(arg)`
const results = input.match(/(?<=\$ctrl\.)[a-zA-Z]+(?=\s|\.|\(|$)/g);
console.log({ results });

But now I try to match only the function calls: fn, fns.

I removed \s|\. from (?=\s|\.|\(|$) but it doesn't work:

/(?<=\$ctrl\.)[a-zA-Z]+(?=\(|$)/g

For this input: account by $ctrl.accounts, it matches accounts but it shouldn't.

How I change that regex to match only functions calling, but only the function after $ctrl.******(?

Upvotes: 0

Views: 96

Answers (1)

SinisaM
SinisaM

Reputation: 303

You must remove the following |, then it will match as you wish. So remove \s|\.| from 1st regex.

const input = `$ctrl.accounts $ctrl.fn() $ctrl.fns(arg) $ctrl.foo.bar $ctrl.bay.bag() $ctrl.bar.fn(arg)`
const results = input.match(/(?<=\$ctrl\.)[a-zA-Z]+(?=\(|$)/g);;
console.log({
  results
})

Upvotes: 1

Related Questions