For creating a multiline string constant you should enclose your string in backticks and not use the backslash within the string. See below code snippet for the differences. s1
will contain no linebreak, but s2
will.
const s1 = "foo \
bar"
const s2 = `foo
bar`
console.log(s1);
console.log(s2);
Thus when applied to your code snippet, you are actually creating a script like the following
var script = "var elements = document.querySelectorAll('...') \
var arr = []; \
for (var i = 0; i < elements.length; i++) { \
arr.push(elements[i].innerText); \
} \
return arr;"
console.log(script);
which is invalid because you have something like the following in it (note the missing semicolon before the second var
)
var elements = document.querySelector(...) var arr = [];
whereas the following snippet produces a valid script
var script = `var elements = document.querySelectorAll('...')
var arr = [];
for (var i = 0; i < elements.length; i++) {
arr.push(elements[i].innerText);
}
return arr;`
console.log(script);
because, when you have a linebreak before the next var
you typically don't need a semicolon.
I'm not really sure, why you get an error about a missing )
, maybe you have a different script which also fails?. Actually the error from that above script should be
Uncaught SyntaxError: Unexpected token 'var'