2

I want to do this:

var todo = "text";

$this.eval(todo).split(/\b[\s,\.-:;]*/).length;

So that this would be the resulting function:

$this.text().split(/\b[\s,\.-:;]*/).length;

I can't figure it out...How do I do this?

2

2 Answers 2

5
var todo = 'text';
$this[todo]().split(/\b[\s,\.-:;]*/).length;
Sign up to request clarification or add additional context in comments.

Comments

0

If you must have it fully dynamic, then you can simply put it all in a string and just eval() it. Something like this:

var obj_name = "text";
var eval_code = "$this."+ obj_name + "(todo).split(/\\b[\\s,\\.-:;]*/).length;";
var result = eval(eval_code);

Also, don't name your variable eval to avoid conflicts with the eval function.

Hope that helps!

2 Comments

eval is not necessary here.
I completely agree. However, the original poster was asking about using a variable as part of a line of code. That's why I said "if you must have it fully dynamic". It's not the right or even good solution, but it answers his question of embedding a variable into a block of code. But yes, it should be clarified that this is not even close to an efficient solution.

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.