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

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

本文关键字:字符 转义字符 字符串 Javascript regex indexOf      更新时间:2023-09-26

我试图更改特定字符,如[ ', ", ' ],因为我在INSERT期间有问题。例如,字符串I'm saying "Hi"将是I''m saying '"Hi'"。这种方法基本上就是在汉字前面加backslash。但我不确定如何用正则表达式做到这一点。

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

你知道怎么做吗?

这应该是你想要的:

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

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

您可以使用$1, $表示"保存的组",1表示第一个保存的组:

:

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

工作原理:

/           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