Is there a way to create a function from a string with javascript?
I added a jsperf test for 4 different ways to create a function from string :
Using RegExp with Function class
var func = "function (a, b) { return a + b; }".parseFunction();
Using Function class with "return"
var func = new Function("return " + "function (a, b) { return a + b; }")();
Using official Function constructor
var func = new Function("a", "b", "return a + b;");
Using Eval
eval("var func = function (a, b) { return a + b; };");
http://jsben.ch/D2xTG
2 result samples:
Given a string describing a Javascript function, convert it to a Javascript function
There's also the Function object.
var adder = new Function("a", "b", "return a + b");
How to turn a String into a JavaScript function call?
Seeing as I hate eval, and I am not alone:
var fn = window[settings.functionName];
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
Edit: In reply to @Mahan's comment:
In this particular case, settings.functionName
would be "clickedOnItem"
. This would, at runtime translate var fn = window[settings.functionName];
into var fn = window["clickedOnItem"]
, which would obtain a reference to function clickedOnItem (nodeId) {}
. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id)
, which equals clickedOnItem(t.parentNode.id)
, which was what the OP wanted.
More full example:
/* Somewhere: */
window.settings = {
/* [..] Other settings */
functionName: 'clickedOnItem'
/* , [..] More settings */
};
/* Later */
function clickedOnItem (nodeId) {
/* Some cool event handling code here */
}
/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
as window.settings.functionName. In this case, we use the fact that window
is the implied scope of global variables. */
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
Create multiple functions from one javascript source as string
When running in a browser, you can dynamically add a script
element and execute it with createContextualFragment:
function executeCode(code) { document.head.appendChild( document.createRange().createContextualFragment('<script>' + code + '<\/script>') );}
// Democonst code = `function func1(){ console.log('This comes from func1')}
function func2(){ console.log('This comes from func2')}
function func3(){ console.log('This comes from func3')}`;
executeCode(code);
func1();func2();func3();
How to write a JavaScript function that takes a string and print out each letter of that string?
charAt accepts the character's index in the string as a parameter, not the character itself.
function myFunc(str) { for (var i = 0; i < str.length; i++) { console.log(str.charAt(i)); }}myFunc('abc');
How to execute a JavaScript function when I have its name as a string
Don't use eval
unless you absolutely, positively have no other choice.
As has been mentioned, using something like this would be the best way to do it:
window["functionName"](arguments);
That, however, will not work with a namespace'd function:
window["My.Namespace.functionName"](arguments); // fail
This is how you would do that:
window["My"]["Namespace"]["functionName"](arguments); // succeeds
In order to make that easier and provide some flexibility, here is a convenience function:
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
You would call it like so:
executeFunctionByName("My.Namespace.functionName", window, arguments);
Note, you can pass in whatever context you want, so this would do the same as above:
executeFunctionByName("Namespace.functionName", My, arguments);
how to create a function that receives a string abcbdbd?
An example using map
const str = "abcbdef";
const array = str.split("");
const output = array.map((_, idx, arr) => arr.slice(0, idx + 1).join("."));
console.log(output);
JavaScript How to Create a Function that returns a string with number of times a characters shows up in a string
let str = prompt('type a string ') || 'taco'
function getcount(str) {
str = str.split('')
let obj = {}
for (i in str) {
let char = str[i]
let keys = Object.getOwnPropertyNames(obj)
if (keys.includes(char)) {
obj[char] += 1
} else {
obj[char] = 1
}
}
let result = ''
Object.getOwnPropertyNames(obj).forEach((prop) => {
result += prop + obj[prop]
})
return result
}
console.log(getcount(str))
Is there a way to create an arrow function from a string with javascript?
You can use eval
to execute a string as code.
eval("() => { console.log('no') }")();
Or if you need some string interpolation:
const foo = 'bar';
eval(`() => { console.log('${foo}') }`)();
Be careful of malicious injection.
Edit: OP, you should be able to extrapolate what you need to do from here.
Related Topics
JavaScript Math, Round to Two Decimal Places
Recursive Matching with Regular Expressions in JavaScript
Load Jquery with JavaScript and Use Jquery
What Does the @ Mean Inside an Import Path
Chrome, JavaScript, Window.Open in New Tab
Moment Js Date Time Comparison
JavaScript - Populate Drop Down List with Array
Get Client Time Zone from Browser
Angularjs - Any Way for $Http.Post to Send Request Parameters Instead of JSON
What's the Cause of the Error 'Getaddrinfo Eai_Again'
Test If Event Handler Is Bound to an Element in Jquery
Optional Chaining in JavaScript
Download and Open PDF File Using Ajax
What Is the Instanceof Operator in JavaScript