2012-03-29 63 views
0

我對javascript的替換方法有問題。我有一個字符串是:使用替換方法javascript

string1 = one|two|three|four; 

我想替換(「|」和「,」);

我想:

string1.replace("|", ","); 

但僅替換第一次出現。我也試過:

string1.replace(/|/g,","); 

和結果是:

string1 = "o,n,e,|,t,w,o,|,t,h,r,e,e,"; 

我怎樣才能讓下面的一個?

string1 = "one,two,three"; 

非常感謝, tinks

回答

4

|是正則表達式中的一個特殊字符。您需要使用反斜槓進行轉義。

string1.replace(/\|/g,","); 

Live example

4

|是在正則表達式特殊字符,這使得左,右操作數之間的或選擇,你必須用一個反斜槓逃脫它用它作爲文字字符。

string1.replace(/\|/g,","); 

string1 = "one|two|three|four"; 
"one|two|three|four" 
string1.replace(/\|/g, ","); 
"one,two,three,four" 
2

你沒有逃脫正則表達式的豎線:

var string1 = "one|two|three|four"; 
string1.replace(/\|/g,",") 
+0

我看晚了,現在黨......黨研發。 – kiswa 2012-03-29 16:05:23

+0

你需要知道這個東西我的心臟,否則你永遠不會有競爭力,所以哈哈 – 2012-03-29 16:10:08

+0

我總是認爲我知道,但我仍然需要檢查確認。可能爲什麼我還低於1K。好吧! :) – kiswa 2012-03-29 17:09:16