简体   繁体   中英

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.

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

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM