skip to Main Content

Inside of the parentheses there will be a web link which is a string between single quotes.

The name of the function will always be the same.

For example if I have my_func('https://old.reddit.com') the string my_func( and ) should be matched and 'https://old.reddit.com' should not.

The best thing I can come up with is my_func((?=[^)]+)).

2

Answers


  1. You could use lookbehind and lookahead
    and match anything that is not a quote (one or more times) until a closing quote and closed brace:

    const getFnArg = (str) => str.match(/(?<=bmy_func(['"`])[^'"`]+(?=['"`]))/)?.[0];
    console.log(getFnArg(`my_func('https://old.reddit.com')`))  // "https://old.reddit.com"
    console.log(getFnArg(`my_func('whatever')`))  // "whatever"
    console.log(getFnArg(`my_func(noquotes)`))    // undefined
    console.log(getFnArg(`my_func('')`))          // undefined
    console.log(getFnArg(`my_func()`))            // undefined

    Regex1010.com demo

    Or a simpler example without lookbehind/ahead:

    const getFnArg = (str) => str.match(/bmy_func(['"`]([^'"`]+)['"`])/)?.[1];
    console.log(getFnArg(`my_func('https://old.reddit.com')`))  // "https://old.reddit.com"
    console.log(getFnArg(`my_func('whatever')`))  // "whatever"
    console.log(getFnArg(`my_func(noquotes)`))    // undefined
    console.log(getFnArg(`my_func('')`))          // undefined
    console.log(getFnArg(`my_func()`))            // undefined
    Login or Signup to reply.
  2. You can use .+?.

    my_func(.+?)
    

    This will match your static text, and allow for any value within the opening and closing parentheses.

    The ? will modify the +, making it a lazy-quantifier.
    This is in the case you have text with more than one my_func match, the balanced parenthesis will be matched, and not the adjacent match’s.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search