DijkeMark
DijkeMark

Reputation: 1306

Javascript regex - getting function name from string

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.

Upvotes: 3

Views: 6563

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

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) {

}

Upvotes: 3

gurvinder372
gurvinder372

Reputation: 68393

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

`function multiply($number) {
    return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]

Upvotes: 4

Related Questions