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?

delphi
  • 10,705
  • 5
  • 22
  • 18
  • possible duplicate of [How do I call a dynamically-named method in Javascript?](http://stackoverflow.com/questions/969743/how-do-i-call-a-dynamically-named-method-in-javascript) and [others](http://stackoverflow.com/search?q=javascript+call+methods+dynamically) – Felix Kling Aug 13 '11 at 15:49
  • Why do you need to call it dynamically like this? – Jakub Arnold Aug 13 '11 at 15:49

2 Answers2

5
var todo = 'text';
$this[todo]().split(/\b[\s,\.-:;]*/).length;
Dogbert
  • 212,659
  • 41
  • 396
  • 397
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!

Michael Petrov
  • 2,247
  • 15
  • 15
  • `eval` is not necessary here. – Felix Kling Aug 13 '11 at 15:53
  • 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. – Michael Petrov Aug 13 '11 at 15:56