Tip: Prevent a string from being escaped in JavaScript

Angelos Chalaris · JavaScript, String · Jun 17, 2021

By default, when JavaScript sees an escape character (\), it will escape the character after it. However, there are cases where you might not want this behavior (e.g. when you want to store a Windows path as a string). For these cases, you can use a template literal and the String.raw() tag function:

const path = `C:\web\index.html`; // 'C:web.html'

const unescapedPath = String.raw`C:\web\index.html`; // 'C:\web\index.html'

Recommended snippets & collections

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Escape HTML

    JavaScript, String

    Escapes a string for use in HTML.

  • Unescape HTML

    JavaScript, String

    Unescapes escaped HTML characters.

  • Escape RegExp

    JavaScript, String

    Escapes a string to use in a regular expression.