`“n”` can't run in `new Function()`


`“n”` can't run in `new Function()`



I want to run code dynamiclly, without using <script>,so I used new Function,but there is a problem when I write n :


<script>


new Function


n


function run (code) {
(new Function(code))()
}

run('console.log("run well")') // it work well
run('console.log("nError")') // error



the result is:
error


Uncaught SyntaxError: Invalid or unexpected token
at new Function (<anonymous>)
at run (<anonymous>:2:3)
at <anonymous>:1:1



And we can find the reason in console: the 'n' has been turn to a new line


(function() {
console.log(" // error here
Error")
})



so using ` to replace " can solve this problem:


run(`console.log("nWell")`)

(function() {
console.log(` // work here
Error`)
})



but it is not suitable that using ` in production, so if there other way to let it well done ?





Use double backslashes to indicate a literal backslash. But don't use new Function in the first place
– CertainPerformance
Jul 2 at 2:52


new Function




3 Answers
3



Since the function body is a string, n will actually be converted to a newline character. You need to escape it by using n.


n


n




function run(code) {
(new Function(code))()
}

run('console.log("run well")') // it work well
run('console.log("nError")') // error





I got it ~ thanks 😁
– Ronk Tsang
Jul 2 at 5:05



This is because you forgot to escape the n as n.


n


n



You can re write your code as


function run (code) {
(new Function(code))()
}

run('console.log("run well")')
run('console.log("nError")')



Console will be



run well



Error



Please try this you will get the output.



Note Below is the escaping chars in detail



JavaScript uses the (backslash) as an escape character for:1[2]



more details about escape characters



I suggest you better fix it in the function level than fix all the inputs to the function



You can modify your function to escape any n by str.replace


n


str.replace


function run(code) {
(new Function(code.replace(/n/g, "n")))()
}



This will escape any number of occurrences for the n in code by n.


n


code


n



Hope this helps!






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages