0

I'm trying to change particular characters such as [ ', ", \ ] because I have a problem during INSERT. For example, the string I'm saying "Hi" will be I\'m saying \"Hi\". So basically this method is adding backslash in front of the characters. But I'm not sure how to do this with regex.

I was thinking to do this with IndexOf but the index of the string is changed when I add the backslash to the string.

Any idea how to do this?

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
KimCrab
  • 2,231
  • 4
  • 15
  • 20

2 Answers2

1

This should do exactly what you want:

str = 'I\'m saying "Hi" \\ abc';
str = str.replace(/\\/g, '\\\\').replace(/(['"])/g, '\\$1');

but if you're using SQL, I would really look into prepared statements: https://github.com/felixge/node-mysql#escaping-query-values

Matt Parlane
  • 453
  • 2
  • 11
0

You can use $1 the $ means "saved group", and 1 means the first saved group:

So:

string.replace( /(['"\\])/g, "\\$1" )

How this works is:

/           Start RegEx
  (         Start "saved" or capturing group
    ['"\\]  Matches any of the characters between []
  )         End "saved" group
/g          End RegEx, g means "global" which means it will match multiple times instead of just the first
Downgoat
  • 13,771
  • 5
  • 46
  • 69