2

我正在尝试使用 javascript 的替换函数来替换字符串。但它只是取代了第一个实例。所以当我使用正则全局表达式时,

var result = 'moaning|yes you|hello test|mission control|com on'.replace(/|/g, ';');

我得到:http: //jsfiddle.net/m8UuD/196/

我想得到:

呻吟;是的你;你好测试;任务控制;com on

4

5 回答 5

6

只需逃离管道:

 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');

在这里,您将找到通常应该转义的正则表达式特殊字符列表

于 2013-04-05T19:34:46.473 回答
3
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
于 2013-04-05T19:34:39.327 回答
2

您还可以使用.split()and .join()

'moaning|yes you|hello test|mission control|com on'.split('|').join(';')
于 2013-04-05T19:36:05.467 回答
1

你需要逃避'|' 像:

var result = 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');

http://jsfiddle.net/PM4PT/

于 2013-04-05T19:35:46.853 回答
1

许多字符是保留的,因为在正则表达式中具有特殊含义,因此要使用其中一个,您需要通过\在特殊字符之前放置一个反斜杠来“转义”它。这些都是:

(   start of a sub-expression
)   end of a sub-expression
{   start of repetition range
}   end of a repetition range
[   start of a character set
]   end of a character set
+   one or more repetitions
*   zero or more repetitions
^   start of string
$   end of string
|   "or" connection between alternatives
\   start of special code or escape
/   start or end of regexp pattern

例如,匹配所有开放方括号的正则表达式是/\[/(注意反斜杠)。如果您需要查找反斜杠,则必须在其前面添加一个反斜杠(因此将其加倍)。

不幸的是,没有用于“转义”所有特殊字符的预定义 Javascript 函数。

于 2013-04-05T19:47:13.863 回答