mathiasbynens / jsesc

Given some data, jsesc returns the shortest possible stringified & ASCII-safe representation of that data.
https://mths.be/jsesc
MIT License
716 stars 53 forks source link

When quote = backtick, backtick characters are not escaped #45

Closed evan-dickinson closed 5 years ago

evan-dickinson commented 5 years ago

In this code, backtick characters are not escaped:

jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
          'quotes': 'backtick'
});

Expected result:

'\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.'

Actual result:

'`Lorem` ipsum "dolor" sit \'amet\' etc.'

The cause of the problem is in regexWhitelist. The backtick character is in the whitelist, so the if statement at line 265 fires, and the code never gets to the special-case handling for the backtick. I updated the whitelist so that it doesn't include the backtick.

mathiasbynens commented 5 years ago

Hmm, I disagree with the expected result; the single quotes should not be escaped within template literals:

'\\`Lorem\\` ipsum "dolor" sit 'amet' etc.'
evan-dickinson commented 5 years ago

I've updated data.js as you requested.

The reason the expected result string has backslashes before the single quotes is because it's a single-quoted string literal, not a template literal. (It's a subtle difference, and easy to miss 😀.)

mathiasbynens commented 5 years ago

Ooh, gotcha :) I see.

Thanks for the patch, @evan-dickinson!