Robin Malfait

May 5, 2024

`String.raw`, and embedding other languages

According to MDN:

The String.raw static method is a tag function of template literals.

A bit of a mouthful, but it allows you to call the String.raw function using the tagged template literal syntax:

let myString = String.raw`My string goes here`

console.log(myString) // 'My string goes here'

This doesn't seem very useful at first, but it has some cool properties that can be useful in your day to day work.

Imagine you are working with Windows file paths, and you want to use it in a string, you would have to write the path separator \ as \\ instead:

let myPath = 'C:\\Users\\me\\Documents\\file.txt'

console.log(myPath) // 'C:\\Users\\me\\Documents\\file.txt'

The reason why is that \ is used to escape other characters. If you want the literal \ character, you have to escape the escape character.

But with String.raw that's not the case, and you can write the path as you would expect it to be written:

let myPath = String.raw`C:\Users\me\Documents\file.txt`

console.log(myPath) // 'C:\\Users\\me\\Documents\\file.txt'

Embedding other languages

While this is cool, there is another use case for String.raw that is even better. You can use it to embed other languages in your JavaScript strings. Some editors (even GitHub's) have support for syntax highlighting for these languages.

And the best part of all is that formatting tools like Prettier will format these strings for you correctly, because we gave some semantic meaning to the otherwise raw string.

// Without the use of `String.raw`
let myUnstyledCss = `
  .example {
    background-color: red;

    &:hover {
      background-color: blue;
    }
  }
`

// With the use of `String.raw`
let css = String.raw

let myStyledCss = css`
  .example {
    background-color: red;

    &:hover {
      background-color: blue;
    }
  }
`

console.log(myStyledCss)
// .example {
//   background-color: red;

//   &:hover {
//     background-color: blue;
//   }
// }

This is something we use in the Tailwind CSS codebase in numerous places:

Editor integrations for syntax highlighting:

Summary

Next time you need to use raw \ characters or embed another language in your JavaScript strings, consider using String.raw. It will make your code more readable and maintainable especially when used with Prettier.

👨‍💻

Copyright © 2024 Robin Malfait. All rights reserved.