Javascript regex to avoid quotes (but not to escape already escaped quotes)

I am looking for a JavaScript regular expression that will escape single quotes, but should not avoid single quotes that are already escaped.

+4
source share
4 answers

Ideally, you want each match to start exactly where the previous match ended. Otherwise, it is too easy to get out of sync with escape sequences. @outis regex is close, but it cannot escape the second single quote in '\\' . After the first match, it must match at least one reverse callback and one single quote, which it cannot do. If there are more characters, it skips ahead and begins to match after the second single quote.

Try instead:

 result = subject.replace(/([^'\\]*(?:\\.[^'\\]*)*)'/g, "$1\\'"); 

This is an example of a Friedl "expanded cycle" template:

normal * (special normal *) *

[^'\\]* is the "normal *" part; it absorbs any number of characters except single quotes or backslashes. If the next character is a backslash, \\. ("special") consumes this, and the next character (backslash, single quote, or something else) and [^'\\]* captures again. Repeat as necessary.

The key point is that the regular expression never skips forward, and it never returns. If he sees a backslash, he always consumes this and the next character, so he never goes out of sync.

+14
source

If there is an even number of backslashes, they only quote each other. Thus, a character is quoted if it has an odd number of previous backslashes. Since JS does not support lookbehind, you will need to grab the leading backslash and include it in the replacement.

 var escquote = /((^|[^\\])(\\\\)*)'/g "a ' b \' c \\' d".replace(escquote, "$1\\'") 

However, if this is for any security purpose, this is the wrong approach for a number of reasons. Firstly, if you do this client side, it is unsafe. Secondly, quoting should be processed when data is sent to the subsystem using the methods provided by the subsystem. For example, if the data enters the relational database, you must use the prepared instructions and parameterize the variable data. Prepared operator parameters are not vulnerable to injection.

+4
source

You can write:

 var escaped = original.replace(/\\['\\]|'/g, function (s) { if (s == "'") return "\\'"; else return s; }); 

If there is a continuous sequence of screened screens, it skips all of them. If there is a "\" at the end, then the quote has already run away and is also skipped. If there is a "" at the end, the quote will be hidden.

+3
source

Here is the solution

 /[^\\]\'|^\'/g 
-1
source

Source: https://habr.com/ru/post/1391173/


All Articles