isaachess
isaachess

Reputation: 809

Regex to capture typed information in TypeScript

I'm new to Regex, took some tutorials, having a hard time getting this right.

I'm working on a language support for TypeScript for a text editor, and I need a regex that matches JUST the typing information in a function. For example:

function asdf(param1:type1, param2:type2, param3:type3) {...}

In that, my regex should match 'type1', 'type2', 'type3' etc.

Here's what I'm trying:

\(.+?:(\w).+?\)

Breaks down like this:

\( look for starting parenthesis

.+?: any number of characters up to the colon

(\w) capture group: the next word

.+? There may be additional words after this

\) Close parentheses for the end of the function parameters.

Not sure what I'm doing wrong, but like I said I'm new to regex. Currently it captures the entire stuff, from beginning parens to closing parens. I need it to match JUST the single words after the colon.

NOTE: I want to make sure it only matches words after colons inside parens, so that it doesn't match object key/data combos, which look similar in Javascript.

Thanks!

Upvotes: 1

Views: 1001

Answers (1)

Fabio
Fabio

Reputation: 1980

Try thus

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '')
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES)
  if(result === null)
     result = []
  for(i=0; i< result.length; i++)
      result[i]=result[i].split(":")[1];
  return result
}

how to use

   getParamNames("function asdf(param1:type1, param2:type2, param3:type3) {...}");

reference

How to get function parameter names/values dynamically from javascript

Upvotes: 2

Related Questions