I'm trying to define a function as part of an object and using the same object properties, but I get the error 'SyntaxError: Arg string terminates parameters early'
let x = {};
x.str = 'Hello Wor\nld';
x.a = /\s/g;
x.action = new Function(x.str, x.a, 'return ' + x.str + '.replace(' + x.a + ', "")');
console.log(x.action);
I'm trying to define a function as part of an object and using the same object properties, but I get the error 'SyntaxError: Arg string terminates parameters early'
let x = {};
x.str = 'Hello Wor\nld';
x.a = /\s/g;
x.action = new Function(x.str, x.a, 'return ' + x.str + '.replace(' + x.a + ', "")');
console.log(x.action);
Hello Wor\nld
seems like a rather odd thing to name a function parameter. so does /\s/g
.
– Kevin B
Commented
May 23, 2019 at 21:47
All but the last argument to new Function
should be the parameter names (which must be valid variable names) - they can't have a space in them, or be a regular expression. For example:
new Function('a', 'b', 'return a + b')
results in something like
function(a, b) {
return a + b
Similarly, what you're doing currently:
function foo(Hello Wor
ld, /\s/g) {
// ...
is invalid syntax.
Make a function which accepts no arguments instead:
let x = {};
x.str = 'Hello Wor\nld';
x.a = /\s/g;
x.action = new Function('return `' + x.str + '`.replace(' + x.a + ', "")');
console.log(x.action());
Note that because x.str
is a string, you should enclose it in string delimiters, and that since it contains a newline character too, you should enclose it in backticks.
Better yet, don't use new Function
at all:
let x = {};
x.str = 'Hello Wor\nld';
x.a = /\s/g;
x.action = () => x.str.replace(x.a, '');
console.log(x.action());