在 Javascript 中使用 regex 或 indexOf 更改字符串中的特定字符(转义字符)

Change particular characters (escape characters) in a string by using regex or indexOf in Javascript

我正在尝试更改特定字符,例如 [ ', ", \ ],因为我在 INSERT 期间遇到问题。例如,字符串 I'm saying "Hi" 将是 I\'m saying \"Hi\"。所以基本上这个方法是在字符前面添加 backslash 。但我不确定如何使用正则表达式来做到这一点。

我想用 IndexOf 来做这个,但是当我将 backslash 添加到字符串时,字符串的索引发生了变化。

知道怎么做吗?

这应该完全符合您的要求:

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

但如果您使用的是 SQL,我真的会研究准备好的语句:https://github.com/felixge/node-mysql#escaping-query-values

可以使用</code>,<code>$表示"saved group",1表示第一个保存的组:

所以:

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

这是如何工作的:

/           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