Search code examples
javascriptnode.jsregexpcre

Javascript Regex to match JSDoc string parameter description


Given a JSDoc string, for example:

*\n * This is a doc string\n * @param withArg description of withArg\n * @param withArg2 description of withArg2 \n

I am trying to extract the argument names and description in an app running on Node 8.

This regex: /@param(\s?\w*)(.*?)\\n/ seems to work in a Regex editor. See https://regex101.com/r/uJz0Km/2/.

But when ran like this:

const matchParamsAndDescriptionRegex = /@param(\s?\w*)(.*?)\\n/g;
const matches = matchParamsAndDescriptionRegex.exec(value);

it returns null. Can you guys spot what's wrong ?

Thanks a lot


Solution

  • You must have regular LF symbols in your original string, not two-char sequences of \ and n.

    Use

    /@param\s*\w*(.*)/g
    

    See the regex demo where

    • @param - matches @param
    • \s*\w* - matches 0+ whitespaces and then 0+ word chars
    • (.*) - captures into Group 1 any zero or more chars.

    Sample JS demo:

    var s = "*\n * This is a doc string\n * @param withArg description of withArg\n * @param withArg2 description of withArg2 \n"
    var rx = /@param\s*\w*(.*)/g;
    var res=[], m;
    while (m = rx.exec(s)) {
      res.push(m[1].trim());
    }
    console.log(res);