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
1 Answer
Reset to default 7All 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
版权声明:本文标题:javascript - I am trying to define a new Function with object properties - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745251613a2649857.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论