vostok
vostok

Reputation: 55

extract only the function name(string values) using a single regex expression

I am trying to extract function names from a javascript file using regex. The 2 cases are
Case 1:

{ 'test1': function(){},
  'test2': function(){}
}

Case 2:

{ test1: function(){}
  test2: function(){}
}

Expected result for either case : [test1, test2]

Now when i use this regex expression with this javascript code

contents.match(/(.+)(?=: function\()/g);

The current result i get is

[ '\t\'test1\'',
    '\t\'test2\'']

How i get the expected result : [test1, test2] , without including special characters like \t \'

Thanks in advance

Upvotes: 1

Views: 156

Answers (2)

The fourth bird
The fourth bird

Reputation: 163427

You could make use of 2 capturing groups.

In group 1 match either ' or " and use a backreference \1 to match the same as what is matched in group 1 to prevent function names to start and end with a different quote like 'test1"

In group 2 capture the function name.

(["']?)([^"'\s{}]+)\1\s*:\s*function\(\)

In parts

  • ( Capture group 1
    • ["']? Match an optional ' or "
  • ) Close group
  • ( Capture group 2
  • )\1 Close group 2
  • \s*:\s* Match : between 0+ whitespace chars
  • function\(\) Match function()

Regex demo

const regex = /(["']?)([^"'\s{}]+)\1\s*:\s*function\(\)/gm;
const str = `{ 'test1': function(){},
  'test2': function(){}
}

{ test1: function(){}
  test2: function(){}
}
`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  console.log(m[2]);
}

Upvotes: 0

grodzi
grodzi

Reputation: 5703

capture any string (not a blank space, nor a ' or ") when it may be followed by ' or ", any whitespace, and : function

let contents = `
{ test1:function(){}
  'test2' : function(){}
  "tes-t2": function(){}
  "teè#//st2"   : function(){}
}
`
console.log(contents.match(/([^'"\s]+)(?=['"]?\s*:\s*function\()/g))

Upvotes: 1

Related Questions