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.

6
  • 2
    Just don't get the whole match but only the capturing group. Commented Dec 5, 2017 at 22:26
  • 2
    You'll want to notice that there are many function in javascript that this regex will not match, or in the wrong position. Commented Dec 5, 2017 at 22:27
  • Curious to know what {1} does there in character class. Commented Dec 5, 2017 at 22:27
  • 1
    I think the {1} should be outside of the character class. Commented Dec 5, 2017 at 22:37
  • On the night of a full moon, just past midnight, you might try eval(`(${string})`).name Commented Dec 5, 2017 at 23:34

2 Answers 2

4

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

`function multiply($number) {
    return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]
Sign up to request clarification or add additional context in comments.

1 Comment

This was the simplest solution that worked for me, thanks!
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) {

}

1 Comment

Though it seems to work, the other answer suits my needs slightly better. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.