Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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')`);

about 4 years ago · Juan Pablo Isaza Report

0

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`)'"'"
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!