4

我需要用\'(反斜杠撇号)替换特殊字符'(撇号),但这应该只在字符串之间,除了字符串的开始和结束字符。
eg:msg ='My Son's Daughter';
字符串中可以有多个撇号。我只想替换不是开始和结束字符的字符串中的撇号。

请与我分享任何想法。

4

3 回答 3

4

使用substr()和 正则表达式的组合:

var msg ="'My Son's Daughter'";

msg = msg.substr(0, 1) + msg.substr(1, msg.length-2).replace(/'/g, "\\'") + msg.substr(msg.length-1, 1);

输出:

'My Son\'s Daughter' 

如图所示,仅'替换内部,忽略第一个和最后一个。

于 2013-06-17T10:58:09.097 回答
2

Try

msg = msg.replace(/(.)'(.)/g, "$1\\'$2");

The . at beginning and end will require any character before and after the '.

The () will catch that charachter defined in it (.) to a variable ($1 and $2).

The $1 and $2 represent the catched character of both ().

The \\ escapes/represents a literal \

The / at the start, just before the g defines this as a Regular Expression (regex)

The g is a modifier (global) that will indicate ALL occurrences.

The regex should NOT be put between quotes as if it was a string.

于 2013-06-17T11:00:27.450 回答
0

替换功能就是您所追求的。这应该可以解决问题:

msg = msg.replace(/'/g, "\\'");
于 2013-06-17T10:55:56.580 回答