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

Escape regular expressions #6

Closed mathiasbynens closed 11 years ago

mathiasbynens commented 11 years ago

Here’s how to stringify a regular expression, escaping the source as needed:

var regex = /©/gmi;
var result = '/' + stringEscape(regex.source, options) + '/' +
(regex.global ? 'g' : '') + (regex.ignoreCase ? 'i' : '') + (regex.multiline ? 'm' : '');
mathiasbynens commented 11 years ago

That would still not work when escapeEverything: true is used, as it would escape characters with special meaning, such as [] etc. We could make it so that the regex.source is stringEscaped with escapeEverything: false at all times, though.

mathiasbynens commented 11 years ago

Currently escaping regular expressions works as expected, as long as the original regular expression wasn’t constructed using escape sequences.

E.g. when regex is /\xA9/, regex.source is '\\xA9'. Running that through stringEscape() adds another layer of escaping, which leads to incorrect results.

We could do something like https://github.com/mathiasbynens/mothereff.in/blob/880f773b51200fc901d9159ad5fa369d440b6cae/js-escapes/eff.js#L50-L57 but perhaps it’s just not worth it.