Skip to content

Commit

Permalink
Don't double escape "$" characters that are already escaped (#740)
Browse files Browse the repository at this point in the history
* Don't double escape "$" characters that are alread escaped

Prettier escapes all "$" characters that aren't used for
inline math. This ensures MDX doesn't double escape the
"\$", otherwise "\$" ends up rendered in the document.

Closes #606

* Use proper negative lookahead regex

* Add more tests around dollar escaping

* Make eslint happy
  • Loading branch information
johno authored Sep 4, 2019
1 parent 5a05c71 commit 90da509
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 3 additions & 1 deletion packages/util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ const paramCase = string =>

const toTemplateLiteral = text => {
const escaped = text
.replace(/\\/g, '\\\\') // Escape all "\" to avoid unwanted escaping in text nodes
.replace(/\\(?!\$)/g, '\\\\') // Escape all "\" to avoid unwanted escaping in text nodes
// and ignore "\$" since it's already escaped and is common
// with prettier https://github.com/mdx-js/mdx/issues/606
.replace(/`/g, '\\`') // Escape "`"" since
.replace(/\$\{/g, '\\${') // Escape ${} in text so that it doesn't eval

Expand Down
18 changes: 17 additions & 1 deletion packages/util/test/test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {paramCase, isImportOrExport} = require('..')
const {paramCase, isImportOrExport, toTemplateLiteral} = require('..')

const PARAM_CASE_FIXTURES = [
['ariaHidden', 'aria-hidden'],
Expand Down Expand Up @@ -35,3 +35,19 @@ describe('isImportOrExport', () => {
})
})
})

describe('toTemplateLiteral', () => {
it("doesn't double escape '$'", () => {
// eslint-disable-next-line
const result = toTemplateLiteral('All the \$')

expect(result).toEqual('{`All the $`}')
})

it("escapes string interpolation '${'", () => {
const result = toTemplateLiteral('All the ${')

// eslint-disable-next-line
expect(result).toEqual('{`All the \\${`}')
})
})

1 comment on commit 90da509

@vercel
Copy link

@vercel vercel bot commented on 90da509 Sep 4, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.