admin管理员组

文章数量:1417092

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);
Share Improve this question asked May 23, 2019 at 21:44 Peter PeakPeter Peak 231 silver badge2 bronze badges 1
  • 1 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
Add a ment  | 

1 Answer 1

Reset to default 7

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());

本文标签: javascriptI am trying to define a new Function with object propertiesStack Overflow