Jump to content

How to Run a Method Stored In a Variable


Spr243

Recommended Posts

How can I run a method stored in a variable?

For example, the user selects a method that the user wants it to complete. That method is stuck in the variable, userSelectedMethod.

var userSelectedMethod = "toUpperCase()"

I want the script to run the method that is in the variable. I tried using the following code. (Didn't work, obviously)

/// Attempt 1
var newResult = enteredText.userSelectedMethod;
/// Attempt 2
var newResult = enteredText.Module[userSelectedMethod];
/// Attempt 3
var newResult = enteredText.callback(userSelectedMethod);

I want the newResult to run whatever method the user Selected Method is. What would be the proper and simplest method of accomplishing this?

Note: The variable names and extra steps have been removed and simplified to explain what I'm trying to do.

Link to comment
Share on other sites

  • 2 weeks later...

I not sure why you would want to do this 🤔,

but this might meet your needs.

[code]

<script>
var x = 'String to be changed.';  // initialize variable

const m = new Map();
      m.set('uc',x.toUpperCase());
      m.set('lc',x.toLowerCase());

var str = x+'\n'+m.get('uc')+'\n'+m.get('lc');
alert(str);

// Change variable contents
x = 'Some new string'; 

alert(x+'\n'+m.get('uc')+'\n'+m.get('lc'));

</script>

[/code]

It uses the Map() function to create objects to manipulate your variable.

 

BTW, welcome to the forums.

Edited by JMRKER
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...