0

this is my code

var javascriptCode="function adding(a,b){ return a+b}"

and i want to pick functionName adding from that string how to do that?

i have tried by finding its index as

var indexStart=javascriptCode.indexOf("function ");
var indexEnd=javascriptCode.indexOf("(");
var res = javascriptCode.substring(indexStart, indexEnd);

but i am getting the output as function adding, is their any other way to do this

2
  • Side note: most likely there are much better approaches to achieve your actual goal. Frequently evaluating script from string is sign of security issue. If you really have to do that - consider finding complete JavaScript parser instead of trying to parse string as correct script yourself. Commented Nov 12, 2015 at 6:40
  • @AlexeiLevenkov actually i am using ui-ace and storing that script in string format, but anyhow thanks :) Commented Nov 12, 2015 at 7:09

2 Answers 2

1

You could use regular expression.

var javascriptCode="function adding(a,b){ return a+b}"
var regex = /function\s*([^\(]*)\(/
var matchResult = javascriptCode.match(regex)
var funcName = null;
if (matchResult && matchResult.length) {
    funcName = matchResult[1];
}
console.log(funcName);
Sign up to request clarification or add additional context in comments.

2 Comments

This is an awesome solution. Thank you.:)
Side notes: in a future if you are not sure if you have an answer please post comment instead. (I removed questions from your post).
1

Try like this

var javascriptCode="function adding(a,b){ return a+b}";
var indexStart=javascriptCode.indexOf(" ");
var indexEnd=javascriptCode.indexOf("(");
var res = javascriptCode.substring(indexStart+1, indexEnd);
console.log(res);

JSFIDDLE

1 Comment

Thanks Anik, this one i take it as scond priority :)

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.