2011-09-09 252 views
2

我有一個字符串,我想用空字符串替換某些值。我的字符串是:Javascript字符串替換

"col1=,,,&col2=,&col3=,,&item5,item8," 

我試圖取代「,,,」與‘’

我曾嘗試以下,也沒有喜悅,沒有任何人有任何想法什麼是最好的方式實現這一目標是什麼?

var string = "col1=,,,&col2=,&col3=,,&item5,item8,"; 
var NewCookie = ""; 

NewCookie = string.replace(",,", ","); 
NewCookie = NewCookie.replace(',,,', ','); 
NewCookie = NewCookie.replace(',,&', ','); 

alert(NewCookie); 

感謝

+0

'&ITEM5,item8'不有效的查詢字符串。你能澄清你想要的格式嗎? –

+0

你可以顯示結果你想要什麼? –

回答

1

試試這個功能:

function RemoveConsecutiveCharacter(str, character){ 
    var newStr = ""; 

    $.each(str, function(index){ 
     if(str[index] != character || str[index-1] != character){ 
      newStr += str[index]; 
     } 
    }); 

    return newStr; 
} 

在這裏看到一個例子:http://jsfiddle.net/expertCode/6naAB/

0

這個工作對我來說:

alert(("col1=,,,&col2=,&col3=,,&item5,item8,").replace(',,,',',')); 

編輯:啊,你設置NewCookie爲 「」 那麼你要替換NewCookie東西(也就是 「」),例如2和3. 你必須在你的例子中設置var NewCookie = string;
或做

var NewCookie = string.replace(',,,',','); 
0

您正在更換",,"","導致:

"col1=,,&col2=,&col3=,&item5,item8," 

因此,當你這樣做:

NewCookie = NewCookie.replace(',,,', ','); 

不再有任何",,,"

嘗試重新安排你的替換功能:

NewCookie = string.replace(',,,', ','); 
NewCookie = NewCookie.replace(",,", ","); 
NewCookie = NewCookie.replace(',&', ','); 
3

試試這個:

var result = "col1=,,,&col2=,&col3=,,&item5,item8,".replace(/,+&?/g,','); 

結果字符串是:"col1=,col2=,col3=,item5,item8,"

var result = "col1=,,,&col2=,&col3=,,&item5,item8,".replace(/=?,+&?/g,'=&'); 

結果字符串是:"col1=&col2=&col3=&item5=&item8=&"

var result = "col1=,,,&col2=,&col3=,,&item5,item8,".replace(/,+/g,','); 

結果字符串是:"col1=,&col2=,&col3=,&item5,item8,"

-1
while(str.indexOf(",,")!=-1){ 
    str = str.replace(",,",","); 
}