3

I am trying to get a function name from a string in javascript.

Let's say I have this string:

function multiply($number) {
    return ($number * 2);
}

I am using the following regex in javascript:

/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g

However, what is selected is multiply(. This is wrong. What I want is the word multiply without the the (, though the regex should keep in mind that the function name must be attached an (.

I can't get this done. How can I make the proper regex for this? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work.

DijkeMark
  • 1,284
  • 5
  • 19
  • 41

2 Answers2

4

Just replace last \) with (?=\()

`function multiply($number) {
    return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
3

You can use:

var name = functionString.match(/function(.*?)\(/)[1].trim();

Get anything between function and the first ( (using a non-gredy quantifier *?), then get the value of the group [1]. And finally, trim to remove surrounding spaces.

Example:

var functionString = "function dollar$$$AreAllowedToo () {  }";

var name = functionString.match(/function(.*?)\(/)[1].trim();

console.log(name);

Notes:

  1. The characters allowed in javascript for variable names are way too much to express in a set. My answer takes care of that. More about this here
  2. You may want to consider the posibility of a comment between function and (, or a new line too. But this really depends on how you intend to use this regex.

take for examlpe:

function /*this is a tricky comment*/ functionName // another one
   (param1, param2) {

}
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73