简体   繁体   中英

Convert JavaScript string to JavaScript literal

In Chrome, when you right-click a string on the console, you'll see "copy string as javascript literal" option. This is what I want to have now, in JavaScript.

For example, let's say I have the following text content:

console.log('hoge');

My question is, how can I get something below from the above?

"console.log('hoge');"

I want to do this because, I have a mega bytes of webpack-generated long JavaScript content, and for a reason I need to eval() the script on an other environment, so I want to copy-and-paste the JavaScript literal text to inside the "eval()". (you may suggest exchanging the data not with the literal but with json (json.stringify/parse), I know, but I just prefer the literal way for now)

So is it possible? Thanks.

After noting the advice regarding the security weakness inherent in using eval (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval )

You can achieve what you want by enclosing the entire literal code inside back-ticks and using the resulting string as the eval argument. back tick quotted strings can include line breaks so you should be able to pass your entire code block inside a single set.

Working snippet.

 console.log('hoge'); console.log('another hoge'); eval(`console.log('hoge'); console.log('another hoge')`);

You can easily enclose Javascript in backticks to get a template literal :

eval(`console.log('hoge')`)

But you should also escape backticks inside the Javascript code to handle situations like this:

eval(`console.log(`hoge`)`)  // SyntaxError

As a solution, you can use this bash one-liner :

 sed 's/`/\\`/g' | xargs -0 printf 'eval(`%s`)'
  1. Invoke the command by pressing Enter .
  2. Paste in the Javascript you want to escape and press Enter again.
  3. Press Ctrl+D to finish input.
  4. You will get valid eval() function call with escaped template literal on the output.

You can assign this one-liner command to an alias for easy use:

 alias js_eval_literal="sed '"'s/`/\\`/g'"' | xargs -0 printf '"'eval(`%s`)'"'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM