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

200
Views
How can I avoid control character interpretation in Javascript template string interpolation?

I have a string variable containing a control character (newline). I want to output that variable but with the control character as its literal representation and not interpreted:

console.log(`Using "${nl}" as newline`)

where the nl variable may contain one of \n, \r, or \r\n. The output of this is of course

Using
as newline

but it should be e.g.

Using "\r\n" as newline

I guess I somehow need to construct a string like this

console.log('Using "\\r\\n" as newline')

So I've been trying to escape the backslashes in nl by prepending another backslash using nl.replace() but that doesn't seem to work because the nl variable doesn't actually contain any backslash characters.

Is there a way to do this generically, i.e. without coding explicitly for \n, \r, and \r\n?

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

0

You could remove the double quotes, and use JSON.stringify which also produces those quotes, and which encodes newline characters (and more, such as TAB, BS, FF, and escapes double quote and backslash):

let nl = "\r\n";
console.log(`Using ${JSON.stringify(nl)} as newline`);

// Or with a newline in a template literal:

nl = `
`;
console.log(`Using ${JSON.stringify(nl)} as newline`);

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!