Jump to content

How to Run a Method Stored In a Variable


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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...