Javascript使用正则表达式替换函数

时间:2013-04-05 19:32:41

标签: javascript regex

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

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

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

我想得到:

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

5 个答案:

答案 0 :(得分:6)

简单地逃离管道:

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

Here you'll find the list of regex special characters that you should generally escape

答案 1 :(得分:3)

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

答案 2 :(得分:2)

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

'moaning|yes you|hello test|mission control|com on'.split('|').join(';')

答案 3 :(得分:1)

你需要逃避'|'像:

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

http://jsfiddle.net/PM4PT/

答案 4 :(得分: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

例如,匹配所有空方括号的常规exprerssion是/\[/(注意反斜杠)。如果你需要寻找反斜杠,你必须在它前面加一个反斜杠(所以加倍)。

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