首页 > 解决方案 > `"\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 :

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 ?

标签: javascriptfunction

解决方案


由于函数体是字符串,\n实际上会被转换为换行符。您需要使用\\n.

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

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


推荐阅读