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

后端 未结 4 1201
情歌与酒
情歌与酒 2021-01-13 19:22

I am looking for a JavaScript regex which will escape single quotes but it should not escape single quotes which are already escaped.

4条回答
  •  不思量自难忘°
    2021-01-13 20:19

    If there are an even number of backslashes, they only quote each other. Thus a character is quoted if it has an odd number of preceding backslashes. Since JS doesn't support lookbehind, you'll need to capture the leading non-backslash and include it in the replacement.

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

    However, if this is for any sort of security purposes, it's the wrong approach for a number of reasons. Firstly, if you're doing this client side, it isn't secure. Second, quoting should be handled when data is sent to a subsystem using the methods provided by the subsystem. For example, if the data is going to a relational database, you should use prepared statements and parameterize the varying data. Prepared statement parameters aren't vulnerale to injection.

提交回复
热议问题